BackeasyStringsSwiggyAmazon

Iterative Stack Horizon Solution

Problem Statement

Given an array of integers, find the sum of the two largest distinct numbers in the array.

Example 1
Input
[1, 2, 3, 4, 5]
Output
9

Explanation: Step-by-step: with input [1, 2, 3, 4, 5], we first sort the array in descending order to get [5, 4, 3, 2, 1], then we add the first two distinct numbers which are 5 and 4, giving output 9

Example 2
Input
[10, 20, 30, 40, 50]
Output
90

Explanation: Step-by-step: with input [10, 20, 30, 40, 50], we first sort the array in descending order to get [50, 40, 30, 20, 10], then we add the first two distinct numbers which are 50 and 40, giving output 90

Constraints

  • 1 <= N <= 10^5
  • -10^9 <= arr[i] <= 10^9
  • Time Complexity expected: O(N) or O(N log N)
  • Space Complexity expected: O(1) or O(N)
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Iterative Stack Horizon — Problem Statement & Solution Guide

StringsEasyCharacter Frequency Map
TimeO(n log n)
|
SpaceO(n)

Problem Description

Given an array of integers, find the sum of the two largest distinct numbers in the array.

Examples

Example 1

Input

[1, 2, 3, 4, 5]

Output

9

Explanation: Step-by-step: with input [1, 2, 3, 4, 5], we first sort the array in descending order to get [5, 4, 3, 2, 1], then we add the first two distinct numbers which are 5 and 4, giving output 9

Example 2

Input

[10, 20, 30, 40, 50]

Output

90

Explanation: Step-by-step: with input [10, 20, 30, 40, 50], we first sort the array in descending order to get [50, 40, 30, 20, 10], then we add the first two distinct numbers which are 50 and 40, giving output 90

Constraints

  • 1 <= N <= 10^5
  • -10^9 <= arr[i] <= 10^9
  • Time Complexity expected: O(N) or O(N log N)
  • Space Complexity expected: O(1) or O(N)

Optimal Approach & Strategy

Use Character Frequency Map to maintain a running state in O(N) time and O(1) auxiliary space.

Brute Force Approach

Iterate over all pairs/subarrays using nested loops and calculate the metric in O(N^2) time.

Verified Code Solutions

JavaScript Solution
Time: O(n log n)
function solution(nums) {
    nums = [...new Set(nums)].sort((a, b) => b - a);
    return nums[0] + nums[1];
}

Asked in Top Tech Interviews

SwiggyAmazon

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.