BackeasyArraysHCL

Find Missing Indices Solution

Problem Statement

Given a positive integer n and an array of distinct integers arr, find all indices from 1 to n that are not present in arr.

Example 1
Input
n = 5, arr = [4, 3, 2, 7, 8, 1]
Output
[5]

Explanation: Step-by-step: First, remove duplicates from the array to get [4, 3, 2, 7, 8, 1]. Then, find the missing indices from 1 to n. In this case, the missing index is 5 because the numbers 1 to 4 and 6 to n are either present or out of range.

Example 2
Input
n = 10, arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Output
[]

Explanation: Step-by-step: The array already contains all indices from 1 to n, so there are no missing indices.

Constraints

  • 1 <= n <= 10^5
  • 1 <= arr[i] <= n
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

Find Missing Indices — Problem Statement & Solution Guide

ArraysEasyCyclic Sort / Index Hashing
TimeO(n)
|
SpaceO(n)

Problem Description

Given a positive integer n and an array of distinct integers arr, find all indices from 1 to n that are not present in arr.

Examples

Example 1

Input

n = 5, arr = [4, 3, 2, 7, 8, 1]

Output

[5]

Explanation: Step-by-step: First, remove duplicates from the array to get [4, 3, 2, 7, 8, 1]. Then, find the missing indices from 1 to n. In this case, the missing index is 5 because the numbers 1 to 4 and 6 to n are either present or out of range.

Example 2

Input

n = 10, arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Output

[]

Explanation: Step-by-step: The array already contains all indices from 1 to n, so there are no missing indices.

Constraints

  • 1 <= n <= 10^5
  • 1 <= arr[i] <= n

Optimal Approach & Strategy

Iterate array, use absolute value as index and negate the value at that index. In second pass, any positive value's index + 1 is a missing number. Time O(N), Space O(1).

Brute Force Approach

Use a HashSet to store elements, then loop 1 to N. Space O(N).

Verified Code Solutions

JavaScript Solution
Time: O(n)
function findMissingIndices(n, arr) {
       // Remove duplicates from the array
       let uniqueArr = [...new Set(arr)];
       let missingIndices = [];
       for (let i = 1; i <= n; i++) {
           if (!uniqueArr.includes(i)) {
               missingIndices.push(i);
           }
       }
       return missingIndices;
   }

Asked in Top Tech Interviews

HCL

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.