BackmediumBinary SearchSalesforceUber

Dynamic Parity Sequence Solution

Problem Statement

You are provided with an array nums of length n containing a heterogeneous mix of integers and non-numeric strings. Your objective is to determine the third distinct maximum numerical value present in the array. Non-numeric elements must be completely ignored during the evaluation. If the array contains fewer than three distinct numerical values, return null.

The solution must efficiently process the array to extract the valid integers, identify the unique values, and rank them in descending order. The third element in this sorted unique list represents the target value. If the list of unique integers has a length less than three, the function should terminate early and return null.

Example 1
Input
nums = [5, "a", 3, 1, 4, "b", 2]
Output
1

Explanation: Step 1: Filter out non-numeric elements. The valid integers are [5, 3, 1, 4, 2]. Step 2: Identify distinct values. The set is {1, 2, 3, 4, 5}. Step 3: Sort in descending order: [5, 4, 3, 2, 1]. Step 4: The third distinct maximum is 1.

Example 2
Input
nums = [10, "x", 10, 20, "y", 30]
Output
10

Explanation: Step 1: Filter out non-numeric elements. The valid integers are [10, 10, 20, 30]. Step 2: Identify distinct values. The set is {10, 20, 30}. Step 3: Sort in descending order: [30, 20, 10]. Step 4: The third distinct maximum is 10.

Example 3
Input
nums = ["str", 7, "num", 7, "end"]
Output
null

Explanation: Step 1: Filter out non-numeric elements. The valid integers are [7, 7]. Step 2: Identify distinct values. The set is {7}. Step 3: The size of the distinct set is 1, which is less than 3. Step 4: Return null.

Example 4
Input
nums = [-1, -2, -3, "-4", -5]
Output
-3

Explanation: Step 1: Filter out non-numeric elements. Note that "-4" is a string, so it is ignored. The valid integers are [-1, -2, -3, -5]. Step 2: Identify distinct values. The set is {-1, -2, -3, -5}. Step 3: Sort in descending order: [-1, -2, -3, -5]. Step 4: The third distinct maximum is -3.

Constraints

  • 1 <= nums.length <= 10^5
  • nums[i] is either an integer or a string
  • -10^9 <= integer value <= 10^9
  • The number of distinct integer values in nums is at most 10^5
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

Dynamic Parity Sequence — Problem Statement & Solution Guide

Binary SearchMediumMin Capacity Target
TimeO(n)
|
SpaceO(1)

Problem Description

You are provided with an array nums of length n containing a heterogeneous mix of integers and non-numeric strings. Your objective is to determine the third distinct maximum numerical value present in the array. Non-numeric elements must be completely ignored during the evaluation. If the array contains fewer than three distinct numerical values, return null.

The solution must efficiently process the array to extract the valid integers, identify the unique values, and rank them in descending order. The third element in this sorted unique list represents the target value. If the list of unique integers has a length less than three, the function should terminate early and return null.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Dynamic Parity Sequence"

medium

WHY DOES IT MATTER?

Finding the k‑th order statistic without full sorting is a classic pattern that appears in ranking, leaderboard, and threshold‑based decision problems. Mastering this pattern teaches you to extract critical information from massive streams while keeping memory footprints tiny.

OPTIMIZATION CHALLENGE

The key insight is that only three distinct values can ever influence the final answer, so you can discard all other numbers immediately. By updating three placeholders conditionally, you avoid any sorting, extra data structures, or multiple passes.

REAL-WORLD CONNECTION

Consider a real‑time analytics pipeline that needs to report the top three revenue‑generating products each minute. The stream contains millions of events, many of which are irrelevant (e.g., non‑numeric error codes). Using a constant‑space top‑three tracker mirrors how such systems maintain live leaderboards without persisting the entire event history.

During an interview, write the three‑variable update logic first, then add the distinctness check (e.g., using a small set or explicit comparisons). This order keeps the code simple and avoids subtle bugs where duplicate maxima overwrite each other.

COMPLEXITY AT A GLANCE

⏱ Time:O(n)
💾 Space:O(1)

Core Theory — Why This Approach?

The task reduces to extracting the set of distinct numeric values from a heterogeneous array and identifying the third largest element in that set. A naive scan that sorts the entire list of numbers incurs O(n log n) time and O(n) extra space, which becomes prohibitive when n reaches millions, especially because sorting does unnecessary work for elements that will never be part of the top‑three. The optimal paradigm leverages a single pass with a constant‑size container (often three variables) to maintain the current top three distinct maxima, updating them only when a new candidate exceeds one of the stored values. This approach exploits the order‑statistics property that the third maximum can be determined without full ordering of the data, yielding linear time and O(1) auxiliary space.

When non‑numeric entries are present, they must be filtered out before any comparison. Attempting to cast every element blindly can raise runtime errors, so a type‑check or try‑catch guard is essential. By integrating the filter into the same linear traversal, we avoid a separate O(n) pass, preserving the overall O(n) bound. The combination of type safety, distinctness enforcement (using a set or explicit checks), and constant‑space top‑three tracking forms the optimal solution for this problem.

Interview Questions on This Problem

Q1How would you modify the algorithm to return the k-th distinct maximum instead of the third, while still using O(n) time and O(k) space?

Maintain a min‑heap (or an array of size k) that stores the k largest distinct numbers seen so far. For each numeric element, if it is not already in the container and either the container has fewer than k elements or the element is larger than the smallest in the heap, insert it and evict the smallest when the size exceeds k. This keeps the top k distinct values in O(log k) per insertion, resulting in O(n log k) time and O(k) space, which is optimal for arbitrary k.

Q2Why is it insufficient to sort the numeric values and then pick the third distinct maximum when the input size is huge and memory is limited?

Sorting requires O(n log n) time and typically O(n) additional memory for the sorted copy, which can exceed time limits and cause memory pressure on large datasets. Moreover, sorting processes every element fully even though we only need three values, leading to unnecessary work. A linear‑time, constant‑space approach avoids both the time overhead and the extra memory allocation.

Q3In a distributed system where the array is sharded across multiple nodes, how can you compute the third distinct maximum efficiently?

Each node independently computes its local top three distinct numbers using the constant‑space algorithm. Then a coordinator merges the at most 3 × numNodes candidates, again applying the same top‑three logic. This two‑phase reduction preserves O(N) total work and requires only O(numNodes) communication, making it scalable.

Examples

Example 1

Input

nums = [5, "a", 3, 1, 4, "b", 2]

Output

1

Explanation: Step 1: Filter out non-numeric elements. The valid integers are [5, 3, 1, 4, 2]. Step 2: Identify distinct values. The set is {1, 2, 3, 4, 5}. Step 3: Sort in descending order: [5, 4, 3, 2, 1]. Step 4: The third distinct maximum is 1.

Example 2

Input

nums = [10, "x", 10, 20, "y", 30]

Output

10

Explanation: Step 1: Filter out non-numeric elements. The valid integers are [10, 10, 20, 30]. Step 2: Identify distinct values. The set is {10, 20, 30}. Step 3: Sort in descending order: [30, 20, 10]. Step 4: The third distinct maximum is 10.

Example 3

Input

nums = ["str", 7, "num", 7, "end"]

Output

null

Explanation: Step 1: Filter out non-numeric elements. The valid integers are [7, 7]. Step 2: Identify distinct values. The set is {7}. Step 3: The size of the distinct set is 1, which is less than 3. Step 4: Return null.

Example 4

Input

nums = [-1, -2, -3, "-4", -5]

Output

-3

Explanation: Step 1: Filter out non-numeric elements. Note that "-4" is a string, so it is ignored. The valid integers are [-1, -2, -3, -5]. Step 2: Identify distinct values. The set is {-1, -2, -3, -5}. Step 3: Sort in descending order: [-1, -2, -3, -5]. Step 4: The third distinct maximum is -3.

Constraints

  • 1 <= nums.length <= 10^5
  • nums[i] is either an integer or a string
  • -10^9 <= integer value <= 10^9
  • The number of distinct integer values in nums is at most 10^5

Optimal Approach & Strategy

Iterate once, maintaining three variables for the top three distinct numbers, updating them conditionally; this yields linear time with constant extra space.

Brute Force Approach

Filter out non‑numeric elements, sort the remaining distinct numbers in descending order, and pick the third element; if fewer than three exist, return null.

Verified Code Solutions

JavaScript Solution
Time: O(n)
function solution(nums) {
    const validNums = nums.filter(x => typeof x === 'number' && Number.isFinite(x));
    const uniqueNums = Array.from(new Set(validNums)).sort((a, b) => b - a);
    return uniqueNums.length >= 3 ? uniqueNums[2] : null;
}

Asked in Top Tech Interviews

SalesforceUber

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.