VOOZH about

URL: https://www.geeksforgeeks.org/dsa/number-of-open-tabs/

⇱ Number of Open Tabs - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Number of Open Tabs

Last Updated : 8 Jun, 2026

You are given an array arr[], where each element is either a tab ID or the string "END". If a tab ID appears, toggle its state (open if it's closed, or close if it's open). If "END" appears, close all open tabs. Your task is to determine the number of tabs that remain open after all operations are completed.

Explanation:

Input: arr[] = ["1", "2", "1", "END", "2"]
Output: 1
Explanation: In the above test case, firstly tab 1st is opened then 2nd is opened then 1st is closed then all are closed then again 2nd is opened.

Input: arr[] = ["1", "2", "END"]
Output: 0
Explanation: 1st and 2nd tab is opened then both closed so zero tabs open at last.

[Naive Approach] Simulation with Array - O(n × t) Time and O(t) Space

Simulate tab switching behavior using an array to track currently open tabs. "END" clears all tabs. For any tab name, if already open, close it; if closed, open it. Return number of open tabs at end.


Output
2

[Expected Approach] Simulate using Hash Set - O(n) Time and O(t) Space

Simulate tab switching using a Hash Set for O(1) lookup and modification. "END" clears all tabs. For any tab, if present in set, remove it; if absent, insert it. Return number of open tabs at end.

  • Create hash set openTabs.
  • Traverse each string in arr: If tab == "END" then clear openTabs. Else if tab exists in openTabs, erase it. Else insert tab into openTabs.
  • Return openTabs.size().

Output
2


Comment
Article Tags:
Article Tags: