BackeasyArraysInfosys

First Duplicate Node Solution

Problem Statement

Given an array of integers nodeIds of size n, containing unique identifiers for surveillance nodes, find the first duplicate node ID found, which represents the breached node. If no duplicates are found, return null.

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

Explanation: Step-by-step: with input [2, 1, 2, 5, 3, 2], we iterate through the array and keep track of the node IDs we've seen. The first duplicate node ID we encounter is 2, so we return 2.

Example 2
Input
[1, 3, 4, 5, 6]
Output
null

Explanation: Step-by-step: with input [1, 3, 4, 5, 6], we iterate through the array and keep track of the node IDs we've seen. Since there are no duplicates, we return null.

Constraints

  • 1 <= n <= 10^5
  • array elements are 0 or 1.
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

First Duplicate Node — Problem Statement & Solution Guide

ArraysEasyLinear Scan
TimeO(n)
|
SpaceO(n)

Problem Description

Given an array of integers nodeIds of size n, containing unique identifiers for surveillance nodes, find the first duplicate node ID found, which represents the breached node. If no duplicates are found, return null.

Examples

Example 1

Input

[2, 1, 2, 5, 3, 2]

Output

2

Explanation: Step-by-step: with input [2, 1, 2, 5, 3, 2], we iterate through the array and keep track of the node IDs we've seen. The first duplicate node ID we encounter is 2, so we return 2.

Example 2

Input

[1, 3, 4, 5, 6]

Output

null

Explanation: Step-by-step: with input [1, 3, 4, 5, 6], we iterate through the array and keep track of the node IDs we've seen. Since there are no duplicates, we return null.

Constraints

  • 1 <= n <= 10^5
  • array elements are 0 or 1.

Optimal Approach & Strategy

The optimized approach involves using a linear scan with a time complexity of O(n) to find the breached node.

Brute Force Approach

The brute force approach involves checking each node in the grid one by one to find the breached node.

Verified Code Solutions

JavaScript Solution
Time: O(n)
function solution(nodeIds) {
      const seen = new Set();
      for (const id of nodeIds) {
         if (seen.has(id)) {
            return id;
         }
         seen.add(id);
      }
      return null;
   }

Asked in Top Tech Interviews

Infosys

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.