First Time With Leetcode Problems - #Day1

Removing Duplicates in an Array (10 Days of Code Challenge)

Well, I have heard the doom and gloom of the infamous website....Leetcode and for the first time, I was thrown into the fray of things. Well, although being my first time with algorithmic problems, After hours of literal pain and gruelsome frustration, I finally figured a way through the problem.

1-level.png Wait, this is tagged as easy?! (▰˘︹˘▰)

I would like to explain my approach towards solving this problem.

The Challenge

1_question.png The challenge in question was to create a function which took an array with duplicate elements and then remove the array's duplicate and also an index number which would show where the final result ends (since some languages cannot change array length)

Starting point

Well, the first thing that I quickly did was to choose my language of choice and I was then overwhelmed with the first problem....Where do I even start?? To calm down my nerves, I chose to start by basically outputting the input array,

A pseudocode of my approach would be something like:

array arr[] = {};
index = 0;
while(index < length_of(array)){
  print arr[index];
  // some other code
  index++;
}

Btw, I prefer while loops to for loops (makes it easier to understand what I'm doing) (;´∀`) From these loop, I had some idea that using that using a loop is the way to go

Algorithm

After minutes of extreme thought, I finally came up with an idea to use a loop within a loop was going to be my method of approach (Walking into dangerous territory here...(´~`)). So here is the algorithm, I had in mind:

i = 0;
while (i < length_of_array){ 
  j = 0;
  while(j < i){
    if arr[i] is equal to arr[j]
      break;
    j++;
  }
  if i is equal to j
    print arr[i]
  i++;
}

Testing it out on an external compiler, the code worked! but next came the hard part. How do I put the answers into an existing array instead of a new one?!

The Eureka Moments

After multiple trial and error moments and almost tiring out, I took a look at the challenge question and then after staring at the question for a while, that's when it struck me, I was'nt just supposed to just output the nums array but also add an index k to show where the array has been changed to. The pseudocode would be like:

// Instead of print arr[i]
equate arr[k] to arr [i]
increment arr[k]

1_final.png Finally did it!