Intermediate Level

Implement the findSecondLargestDistinct method that returns the second largest distinct value from the array.

The input contains an integer array nums and its length size. Your task is to return the second largest distinct value in the array.

Duplicate values should be treated as one value. If there is no second distinct value, return -1. For example, in [5,1,9,9,3], the largest distinct value is 9 and the second largest distinct value is 5.

Example 1

Input
nums (int[]) = [5,1,9,9,3]
size (int) = 5
Returns (int) 5

Example 2

Input
nums (int[]) = [4,4,4]
size (int) = 3
Returns (int) -1

Example 3

Input
nums (int[]) = [-1,-5,-3]
size (int) = 3
Returns (int) -3

Keep track of the largest and second largest distinct values while scanning the array.

When a value is greater than the current largest, move the old largest to second largest. When a value is between largest and second largest, update only second largest. Ignore duplicates of the current largest or second largest.

Pseudocode:

function findSecondLargestDistinct(nums, size):
    largest = none
    second = none
    for each value in nums:
        if value == largest or value == second:
            continue
        if largest is none or value > largest:
            second = largest
            largest = value
        else if second is none or value > second:
            second = value
    if second is none:
        return -1
    return second
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.