how to find the second largest number in an array

RMAG news

Hey folks! So, I ran into an interesting challenge on HackerRank today – finding the second largest value in an array. Sounds simple, right? Well, it got a bit tricky with all the edge cases, but here’s how I cracked it:
First off, I had to get my head around the idea that I needed to find the biggest number before I could figure out the second biggest. So, I started by creating a variable called max and set it to 0.

I imagined this as my placeholder for the largest number.
Next, I ran a for loop through the array to find the largest number. Each time I found a number bigger than my current max, I updated max with that number. By the end of this loop, I had the biggest number stored in max.

Now, here’s where the fun part begins. I needed to “remove” this largest number from the array so I could find the next biggest one. So, I ran another for loop and whenever I encountered the number that matched my max, I replaced it with 0. This step ensured that the largest number was no longer in play.

With the largest number out of the way, I ran a third for loop to find the new largest number, which, thanks to my previous step, was actually the second largest number in the original array. And voila, I printed this value.

**
So, that’s how I tackled the problem! It was a bit of a journey, but it was a great learning experience.
**

Please follow and like us:
Pin Share