Find the first value that appears for the second time in [3, 8, 1, 9, 8, 3, 1], first with nested loops and break, then in one pass with a Set.
Solution
main.js
const data = [3, 8, 1, 9, 8, 3, 1];
// 1. Nested loops (O(n²)): for each j, look back for an earlier equal value
let firstRepeat = null;
search: for (let j = 1; j < data.length; j++) {
for (let i = 0; i < j; i++) {
if (data[i] === data[j]) { firstRepeat = data[j]; break search; }
}
}
console.log("nested loops:", firstRepeat);
// 2. One pass with a Set (O(n))
const seen = new Set();
for (const v of data) {
if (seen.has(v)) { console.log("set:", v); break; }
seen.add(v);
}
Output Verified by running it on Node.js
nested loops: 8
set: 8
8 is the first value whose second occurrence comes earliest (index 4). The labelled break stops both loops at once; the Set version remembers what it has seen and is much faster for large inputs.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!