In this and subsequent posts, we shall look at an algorithmic problem related to arrays. (Pls click on the sections in the visual below to expand them.)
❀ ✿ ❀
श्रीः
Learn Algorithms for Interviews
Question
Find the 2nd largest
distinct
value in an array.
For example, what is the 2nd largest distinct value here?
Understanding the Problem
❀ When we are given a question, it is good practice
to first properly understand
what exactly the question expects us to do.
❀ The more clearly we understand the problem,
the better equipped we are to find a correct and efficient solution.
❀ This also creates a good impression in an interview.
It shows that we use a
step-by-step, methodical approach
instead of directly jumping into coding.
Understand
→
Clarify
→
Test examples
→
Solve
Examples to clarify the Question
Example 1
Largest
2nd largest distinct
2nd largest distinct value = 28
The largest value is 42.
The next lower distinct value is 28.
Therefore, the answer is 28.
Example 2
Largest
2nd largest distinct
2nd largest distinct value = 25
The largest value is 42.
It appears twice, but both occurrences represent the
same distinct value.
The next lower distinct value is 25.
Therefore, our answer is 25, not 42.
More Examples to clarify the Question
Example 3
Largest
2nd largest distinct
2nd largest distinct value = 15
The largest value is 24, and it appears twice.
The second-largest distinct value is 15,
even though 15 itself appears several times.
Repetition does not change which value is the
2nd largest distinct value.
Example 4
There is no 2nd largest distinct value.
All elements in the array have the same value,
10.
Therefore, the array contains only
one distinct value.
Hence, a 2nd distinct value does not exist.
✿ ❀ ✿ ❀ ✿
Above, we looked at the problem, and a few examples to understand the question better.
Next in this series: Algorithm for finding 2nd Largest Distinct Value in Array
[You can see a few other posts on Algorithms here: Learn Binary Search, Learn Insertion Sort.]
[Other DSA Interview Q-A: Find Missing Value in Array.]
Leave a Reply