BackmediumArraysFlipkart

NEW OR EXISTING ID 3 Solution

Problem Statement

You are managing a dynamic list of unique integer identifiers. Given an array ids representing the current set of active identifiers and a target integer target, perform a toggle operation on the list. If target is not currently present in ids, append it to the end of the array. If target is already present, remove the first occurrence of target from the array. Return the resulting array after this single toggle operation.

The operation must be performed in-place if possible, or return a new array reflecting the change. The order of elements must be preserved for all elements other than the one being added or removed. If the array becomes empty after removal, return an empty array.

Example 1
Input
ids = [10, 20, 30], target = 40
Output
[10, 20, 30, 40]

Explanation: The target 40 is not found in the array [10, 20, 30]. Therefore, it is appended to the end, resulting in [10, 20, 30, 40].

Example 2
Input
ids = [10, 20, 30], target = 20
Output
[10, 30]

Explanation: The target 20 is found at index 1. It is removed from the array, shifting subsequent elements left. The resulting array is [10, 30].

Example 3
Input
ids = [5], target = 5
Output
[]

Explanation: The target 5 is the only element in the array. It is removed, resulting in an empty array.

Example 4
Input
ids = [], target = 7
Output
[7]

Explanation: The array is empty, so the target 7 is not present. It is appended to the empty array, resulting in [7].

Constraints

  • 0 <= ids.length <= 10^5
  • -10^9 <= ids[i] <= 10^9
  • -10^9 <= target <= 10^9
  • All elements in ids are unique.
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

NEW OR EXISTING ID 3 — Problem Statement & Solution Guide

ArraysMedium
TimeO(n)
|
SpaceO(1)

Problem Description

You are managing a dynamic list of unique integer identifiers. Given an array ids representing the current set of active identifiers and a target integer target, perform a toggle operation on the list. If target is not currently present in ids, append it to the end of the array. If target is already present, remove the first occurrence of target from the array. Return the resulting array after this single toggle operation.

The operation must be performed in-place if possible, or return a new array reflecting the change. The order of elements must be preserved for all elements other than the one being added or removed. If the array becomes empty after removal, return an empty array.

DSA Pattern Breakdown

DSA Pattern Breakdown

"NEW OR EXISTING ID 3"

medium

WHY DOES IT MATTER?

The toggle‑presence pattern appears in caching, feature‑flag systems, and subscription management where an item must be added if missing or removed if present, all while preserving order. Mastering this pattern prevents hidden O(n^2) pitfalls in real‑world codebases.

OPTIMIZATION CHALLENGE

The breakthrough is realizing that you only need a single pass to both detect presence and capture the index, eliminating the need for a second scan or repeated splices. By deferring the mutation until after the scan, you keep the algorithm at the theoretical lower bound of O(n).

REAL-WORLD CONNECTION

Think of a distributed service registry: when a node registers, it is added to the list; when it deregisters, the first entry for that node is removed. The registry must stay ordered for deterministic health checks, mirroring the array toggle operation.

During an interview, write the linear scan first, store the index when you see the target, and break early. Then, based on whether the index is -1, either push or splice. This shows you understand early exit, in‑place mutation, and constant‑space reasoning.

COMPLEXITY AT A GLANCE

⏱ Time:O(n)
đź’ľ Space:O(1)

Core Theory — Why This Approach?

The problem boils down to a membership test followed by a conditional mutation of a linear container. In the naive world, one might repeatedly scan the array for the target, and on each match perform costly splice operations that shift elements, leading to quadratic behavior when the operation is embedded in a loop. However, because we only need to toggle a single element once, the optimal paradigm is a single linear pass: locate the first occurrence (if any) while simultaneously tracking its index, then either append or remove based on the discovery. This approach leverages the fact that array look‑ups are O(1) but deletions are O(n) due to element shifting, so we minimize shifts by performing at most one removal. The overall time complexity remains O(n) – the lower bound for any algorithm that must inspect an unsorted list to decide presence – while using O(1) auxiliary space.

When the input size grows to millions, a repeated O(n) scan per operation would be prohibitive, but a single pass per toggle scales linearly and fits comfortably within typical memory limits. The key insight is to avoid nested loops or repeated splicing; instead, capture the index of the target during the first traversal and defer the mutation until after the scan. This pattern—"scan‑once, mutate‑once"—is a staple in array manipulation problems where order must be preserved.

If the problem were extended to many toggles, a hybrid structure (hash map + doubly linked list) would achieve amortized O(1) updates, but for a solitary toggle the linear scan is both simplest and optimal. Understanding when to stop over‑engineering and when a single pass suffices is a critical skill for senior engineers.

Interview Questions on This Problem

Q1How would you modify your solution if the list could contain duplicate identifiers and you needed to toggle all occurrences of the target?

First, scan the array to collect indices of every occurrence of the target. If the list of indices is empty, append the target once. If not, remove elements at those indices in reverse order to avoid index shift issues. This still runs in O(n) time and O(k) extra space where k is the number of occurrences.

Q2Explain how you would adapt the algorithm to support a stream of toggle operations efficiently.

Maintain a hash set for O(1) membership checks and a doubly linked list (or array with lazy deletions) to preserve order. On toggle, check the set: if absent, add to both set and list tail; if present, locate the node via a map from value to node reference and remove it in O(1). This yields amortized O(1) per operation with O(n) total space.

Q3Why is it insufficient to use JavaScript's Array.includes followed by push or splice for large inputs?

Array.includes performs a linear scan, and splice on the first match also shifts all subsequent elements, both O(n). When combined, they still result in O(n) per operation, which is acceptable for a single toggle but becomes costly if many toggles are performed. Moreover, splice mutates the original array in place, which can lead to bugs if the same reference is used elsewhere.

Examples

Example 1

Input

ids = [10, 20, 30], target = 40

Output

[10, 20, 30, 40]

Explanation: The target 40 is not found in the array [10, 20, 30]. Therefore, it is appended to the end, resulting in [10, 20, 30, 40].

Example 2

Input

ids = [10, 20, 30], target = 20

Output

[10, 30]

Explanation: The target 20 is found at index 1. It is removed from the array, shifting subsequent elements left. The resulting array is [10, 30].

Example 3

Input

ids = [5], target = 5

Output

[]

Explanation: The target 5 is the only element in the array. It is removed, resulting in an empty array.

Example 4

Input

ids = [], target = 7

Output

[7]

Explanation: The array is empty, so the target 7 is not present. It is appended to the empty array, resulting in [7].

Constraints

  • 0 <= ids.length <= 10^5
  • -10^9 <= ids[i] <= 10^9
  • -10^9 <= target <= 10^9
  • All elements in ids are unique.

Optimal Approach & Strategy

Perform a single linear scan, capture the first index of the target, and after the scan either push the target or splice it out, achieving O(n) time with O(1) extra space.

Brute Force Approach

Repeatedly call indexOf to find the target, then use splice to delete or push to add, resulting in multiple passes over the array.

Verified Code Solutions

JavaScript Solution
Time: O(n)
function toggleID(ids, target) {
    const index = ids.indexOf(target);
    if (index === -1) {
        ids.push(target);
    } else {
        ids.splice(index, 1);
    }
    return ids;
}

const ids = [10, 20, 30];
const target = 40;
console.log(toggleID(ids, target));

Asked in Top Tech Interviews

Flipkart

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.