DSA interview question
A marathon's live tracker lists the runners' current speeds from the front of the pack to the back, and marks a runner as a leader if nobody behind them is faster, meaning their speed is greater than or equal to every speed to their right. The last runner is always a leader. Checking every runner against everyone behind them is O(n²). Scanning from the right instead, keeping the maximum seen so far, identifies all leaders in one pass.
Example: [16, 17, 4, 3, 5, 2] → [17, 5, 2].
vector<int> leaders(const vector<int>& a); // leaders in their original left-to-right order
Input a | Output | Explanation |
|---|---|---|
[16, 17, 4, 3, 5, 2] | [17, 5, 2] | |
[10, 4, 2, 4, 1] | [10, 4, 4, 1] | Equal to the maximum on the right still counts |
[5, 4, 3, 2, 1] | [5, 4, 3, 2, 1] | Every element is a leader |
[1, 2, 3, 4, 5] | [5] | Only the last element |
[7] | [7] | |
[1, 1, 1] | [1, 1, 1] |
(Confirm: a leader is greater than or equal to every element to its right (the GeeksforGeeks definition); output in original order.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in