C
C#ByGoalZ

IndexOutOfRange Leetcode help

Hey, having an issue with my leetcode problem. I know that its supposed to be a bitwise XOR operation but I tried a different algorithm as im not that advanced yet. "Given a non-empty array of integers nums, every element appears twice except for one. Find that single one."
public class Solution {
public int SingleNumber(int[] nums) {
int[] nums2 = new int[nums.Length];

if (nums.Length == 1) {
return nums[0];
}
for (int i = 0; i < nums.Length; i++) {
if (Array.IndexOf(nums2, nums[i]) < 0) {
nums2[i] = nums[i];

} else {
var x = Array.IndexOf(nums2, nums[i]);
nums[x] = 0;
nums[i] = 0;
}
}

var index = Array.FindIndex(nums, value => value != 0);
return nums[index];





}
}
public class Solution {
public int SingleNumber(int[] nums) {
int[] nums2 = new int[nums.Length];

if (nums.Length == 1) {
return nums[0];
}
for (int i = 0; i < nums.Length; i++) {
if (Array.IndexOf(nums2, nums[i]) < 0) {
nums2[i] = nums[i];

} else {
var x = Array.IndexOf(nums2, nums[i]);
nums[x] = 0;
nums[i] = 0;
}
}

var index = Array.FindIndex(nums, value => value != 0);
return nums[index];





}
}
Error:Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
T
TheRanger16d ago
which line gave you that error?
B
ByGoalZ16d ago
It doesnt show, im using the leetcode editor so :/
T
TheRanger16d ago
well that error only appears when you're trying to access the array out of its bounds
B
ByGoalZ16d ago
it also doesnt show me for which testcase its failing
T
TheRanger16d ago
eg if array's size is 5 and you tried to access element 6, u get this error you can only pick elements from 1 to 5
B
ByGoalZ16d ago
Yea, chatgpt said it might be due to this line "var index = Array.FindIndex(nums, value => value != 0);" as it will return -1 if there is no element thats not zero
T
TheRanger16d ago
yeah no i wouldnt rely on chatgpt 100%
B
ByGoalZ16d ago
but there must be an element thats not zero Yea ik but I have no idea what else it could be
T
TheRanger16d ago
maybe the arrays size is 0
B
ByGoalZ16d ago
And it worked for 5 testcases so the algorithm shouldnt be completely false
T
TheRanger16d ago
use Console.WriteLine to debug the array's size
B
ByGoalZ16d ago
well theres written "non-empty arrays" alr
T
TheRanger16d ago
just test
B
ByGoalZ16d ago
3
T
TheRanger16d ago
this might be the problem
var x = Array.IndexOf(nums2, nums[i]);
var x = Array.IndexOf(nums2, nums[i]);
x is probably -1 then this nums[x] = 0; threw the error or this too
var index = Array.FindIndex(nums, value => value != 0);
return nums[index];
var index = Array.FindIndex(nums, value => value != 0);
return nums[index];
B
ByGoalZ16d ago
yea this is what chatgpt said but why would it be -1
T
TheRanger16d ago
well it means it didnt find any number that isnt 0 in the array debug the values of the array
B
ByGoalZ16d ago
alr its [0,0,0] lol how tf
E
exe16d ago
How about step through it with the debugger?
B
ByGoalZ16d ago
wdym by that?
T
TheRanger16d ago
does leetcode even have a debugger?
B
ByGoalZ16d ago
Im wondering what happened if it would be [0,2,2], then the final array would be [0,0,0] which would error
E
exe16d ago
OH ok, I have no idea what is leetcode let me have a quick scan of your code
B
ByGoalZ16d ago
leetcode is a coding challenge website yep this is the issue, original array is [1,0,1]
T
TheRanger16d ago
you are zeroing your array with nums[i] = 0;
B
ByGoalZ16d ago
but how can I solve it
E
exe16d ago
what is this even supposed to do?
B
ByGoalZ16d ago
"Given a non-empty array of integers nums, every element appears twice except for one. Find that single one." yes, is that wrong?
T
TheRanger16d ago
why are you zeroing the values of your array?
E
exe16d ago
and this is your code?
B
ByGoalZ16d ago
every zero is an element thats double, so at the end only the single element is still there, all others are zero. Thats why at the end I return the element that isnt zero Yes, but im aware that its normally done with a XOR expression but I tried doing it on my own
E
exe16d ago
No linq?
B
ByGoalZ16d ago
no , this would be linq with the XOR expression, but I just read that online. public int SingleNumber(int[] nums) => nums.Aggregate((s, a) => s ^ a);
T
TheRanger16d ago
i dont think you need to do bitwise XOR operation just count the values, return the one whose count is 1
E
exe16d ago
I'm sure it's just something like array.Single(x => array.Count(... that sort of thing
T
TheRanger16d ago
GroupBy should work too
E
exe16d ago
yeah
B
ByGoalZ16d ago
wdym count? How do I remember the ones before like, how do I store them
T
TheRanger16d ago
well, there are many ways like using dictionary, linq, or whatever
E
exe16d ago
Given a non-empty array of integers nums, every element appears twice except for one. Find that single one This to me just reads as, assume every number in some given array appears twice except for 1 no need to count everything to make sure, just find the thing which there is only 1 of
B
ByGoalZ16d ago
yea thats what I tried, how would you do it?
T
TheRanger16d ago
if you want to avoid linq, just use a nested for loop or just use linq 🤷 But that wouldnt be much of a challenge
E
exe16d ago
No description
E
exe16d ago
a very simple 1 liner
T
TheRanger16d ago
I usually avoid spoonfeeding its not much of a challenge if someone does it for you
E
exe16d ago
My bad, sorry I've just joined 🙂
B
ByGoalZ16d ago
yea, im not submitting your solutions, just interested. I havent really touched LINQ before so i dont even know what "=>" means 😂 is it like an "if?
T
TheRanger16d ago
thats lambda expression you could just use a nested for loop
E
exe16d ago
Ah ok, linq is just a bunch of .NET methods to make things easier to read and write, reducing the need to write for loops yourself in this case. and yes => is a lambda
B
ByGoalZ16d ago
How?
E
exe16d ago
without linq, you could create exactly the same result by writing for loops yourself. the Single is a method, which iterates through everything in x here. With this fact, you can start your code with a for loop
B
ByGoalZ16d ago
Ok so: Iterate through the array -> then what? I cant just compare the current element to the next one right?
E
exe16d ago
It also takes a lambda returning a bool, known in most languages as a predicate, a condition
B
ByGoalZ16d ago
I did it lol
No description
T
TheRanger16d ago
You can start by wrapping your own Count method nvm then lol
B
ByGoalZ16d ago
Just did this
No description
T
TheRanger16d ago
That's a linq method
B
ByGoalZ16d ago
yea I have used linq before but just simple expressions I always use the => as an if 😂 Imma start to learn it properly tho
T
TheRanger16d ago
That doesnt really answer your challenge you just happened to return 0, which is the correct answer but if leetcode sent you another input, it may not work
B
ByGoalZ16d ago
no, it tests with hundreds of testcases the issue in my code just was that when the single number is a zero, the logic breaks basically
T
TheRanger16d ago
but your elements arent all zero, so the variable will be false
B
ByGoalZ16d ago
they are cuz my code is setting every double int to zero, so just the single number will be left, which if its a zero would be an all zero array
E
exe16d ago
so that means, you iterate from the start of x, to the end. At every iteration you need to know if this number appears once, or more. You could do this with a nested for loop. You'll need to count the occurrences of the occurence in the inner loop Looking at your code, I don't think there is a need to use FindIndex here
T
TheRanger16d ago
what do u mean by double int
B
ByGoalZ16d ago
poor choice of words but every digit that appears twice lol my code is a mess and overcomplicated ik 😂
E
exe16d ago
Beginning programming always is, don't worry 🙂
B
ByGoalZ16d ago
alr, I will try to do it this way and see if the runtime decreases and at the same time its another challenge lol
E
exe16d ago
If you can assume there is only 1 thing in an array which appears once, and the rest twice. You should be able to just have a nested for loop. The inner loop counting the occurences of the element targeted by the outer loop. After the inner loop, but still inside the outer loop, I think you could bail out if ==1
B
ByGoalZ16d ago
ooh thanks
E
exe16d ago
That's OK, there are, as R ^ said, many ways to do it. The cleanest is with linq but probably better to learn things like this without first
B
ByGoalZ16d ago
Thanks, this worked even better and way less code. Gonna try it with LINQ too.
No description
E
exe16d ago
No worries, I sketched out something like this; if you wanted to compare
No description
E
exe16d ago
If you're interested in what's likely, or similarly going on inside those LINQ Maybe not quite as naive, but effectively similar
E
exe16d ago
No description
E
exe16d ago
So actually, the for loops might be a little more efficient with 2 iterations instead of 3 here with LINQ.
Want results from more Discord servers?
Add your server
More Posts
visual studio .net core ironPDFi have problem with export to pdf files. It's works perfectly( create a files and change keyword), bVisual Studio + WPF: "Could Not Load Assembly" despite dlls being available and reference correctThis has been driving me nuts for a day now. It's an intermittent error as had this working fine at how to export datas to json file from mysqlI have datas in mysql I want to move them to a json file. How can I do that?Licensing my programHi, i’m developing a Point Of Sale software and would like to find out possible solutions to manage ✅ Unhandled exception. Cannot print exception string because Exception.ToString() failed.justwhy this error always come in dotnet webapi application version ----- dotnet --version ✅ How to use Dapper with Query ParametersI work a lot with SQL databases such as MySQL, SQLite and PSQL and usually I write my Queries like t✅ transaction in transaction issueI have this error: `The connection is already in a transaction and cannot participate in another trHelp making login function c#Im currently trying to code a login function I have the registration my user is getting saved in thProblems with docker and my app imageI already posted a question that more or less manage to solve but now i have other problem, the thiAttempting to get value from different JSON files with variable keyHello o/ I am attempting to deserilize and obtain the value from a variety of JSON files that contaiHow to display only department fields associated with a selected department in student automationhi, I'm facing a challenge while working on the student automation system. After selecting the deparHelp with DiscordGameSDK in a C# project (no Unity)I am currently trying to develop a plugin for a Unity game. For this I created a C# project, where IMarshal.GetActiveObject("Word.Application") fall in exceptionI'm working on a `.NET Framework` console application, I have added the `Microsoft.Office.Interop.WMigrating to Microsoft.IdentityModel.JsonWebTokens .net6 => .net8Hi, I am migrating a project which uses Duende as identity server + Ocelot gateway from .NET 6 to .NProcess working set is twice as commited managed memoryHi! I have an ASP.NET Core 8 app running on Linux in Docker. It's memory usage is limited by 512M. Resource based authorization with IdentityHello, I have the following setup in my asp.net core project: A `Workspace` model that has a bunch o✅ is .net 8.0 is not compatibleHey hi guys I'm new to this group and .net I just started learning .net I don't have any experience Help with why code is returning this way.Hello, I'm a CS student learning C# for the first time and i'm having some confusion on why my code Named pipe connection over network error (The username or password is incorrect)When running a solution where one machine runs a server and a second machine runs a client connectinDifference algorithm that Git usesHello! Quick rundown: I have a need to detect changes in custom bytecode sequences. Essentially, I