LearnFrenzy
Sign in Take a free test

Loops · Loops Coding Problems · Question 8

First repeated value in JavaScript Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links