Company Corner

Opening and Closing Gates Problem: Wipro Coding Walkthrough

The opening and closing gates problem is a Wipro coding round question based on balanced parentheses. Algorithm, worked solution, and test cases all in one place.

By FACE Prep Team 5 min read
wipro coding-round data-structures stack balanced-parentheses placement-prep wipro-nlth

The opening and closing gates problem is a Wipro coding round question that maps directly to balanced parentheses, a problem every placement-prep student should know cold.

The Problem: Gates as Parentheses

A city’s water reservation system uses opening gates and closing gates. Each opening gate must be matched by a corresponding closing gate, or water leaks and the city is at risk. A closing gate cannot exist without a preceding opening gate, so the system head checks the design before declaring the city safe.

The CS abstraction is exact:

  • Opening gate: (
  • Closing gate: )
  • Valid pair: a ( followed (eventually) by a matching )

Input: A string str consisting only of ( and ) characters.

Output: An integer.

  • Return the count of valid matched pairs if the sequence is safe.
  • Return -1 if the sequence is unsafe: any closing gate appears before its opening gate, or any opening gate is never closed.

Reference table of inputs and expected outputs:

InputOutputReason
()()2Two matched pairs, no unmatched gates
(())2Nested — both pairs matched
()(-1Last ( is never closed
)(-1First ) has no preceding (
()1One matched pair
(empty)0No gates to process

The logic is identical to the classical balanced parentheses problem, which is a standard stack application. One bracket type, one pass.

Stack Algorithm: Step-by-Step

The approach uses a stack to track unmatched opening gates. The rules at each character:

  • If (: push it onto the stack.
  • If ) and the stack is empty: return -1 (closing gate has no matching opener).
  • If ) and the stack is non-empty: pop from the stack and increment the matched-pair counter.
  • After the full pass, if the stack still has items: return -1 (opening gates were never closed).
  • Otherwise return the counter.

Python

def gates_algorithm(s):
    stack = []
    count = 0
    for c in s:
        if c == '(':
            stack.append(c)
        elif c == ')':
            if not stack:
                return -1
            stack.pop()
            count += 1
    if stack:
        return -1
    return count

Java

import java.util.Stack;

public class GatesProblem {
    public static int gatesAlgorithm(String s) {
        Stack<Character> stack = new Stack<>();
        int count = 0;
        for (char c : s.toCharArray()) {
            if (c == '(') {
                stack.push(c);
            } else if (c == ')') {
                if (stack.isEmpty()) return -1;
                stack.pop();
                count++;
            }
        }
        return stack.isEmpty() ? count : -1;
    }
}

Counter Variant: O(1) Space

For this specific problem (single bracket type only), a counter replaces the stack. The counter tracks how many opening gates are currently unmatched.

def gates_counter(s):
    open_count = 0
    matched = 0
    for c in s:
        if c == '(':
            open_count += 1
        elif c == ')':
            if open_count == 0:
                return -1
            open_count -= 1
            matched += 1
    return -1 if open_count > 0 else matched

Both implementations produce identical results for all inputs. The counter variant uses O(1) space. The stack variant generalises to multi-bracket problems like `()[]{}` with a change to the pop-matching logic. For any follow-up question in an interview (“what if there were three bracket types?”), the stack solution is the natural starting point.

Worked Examples and Test Cases

These traces follow the stack implementation. Each step shows the stack state and matched-pair counter after processing one character.

Trace: ()()

  • Step 1: ( — push. Stack: ['('], matched: 0
  • Step 2: ) — stack non-empty, pop. Stack: [], matched: 1
  • Step 3: ( — push. Stack: ['('], matched: 1
  • Step 4: ) — stack non-empty, pop. Stack: [], matched: 2
  • End: stack empty. Return 2.

Trace: (())

  • Step 1: ( — push. Stack: ['('], matched: 0
  • Step 2: ( — push. Stack: ['(', '('], matched: 0
  • Step 3: ) — pop. Stack: ['('], matched: 1
  • Step 4: ) — pop. Stack: [], matched: 2
  • End: stack empty. Return 2.

Trace: ()(

  • Step 1: ( — push. Stack: ['('], matched: 0
  • Step 2: ) — pop. Stack: [], matched: 1
  • Step 3: ( — push. Stack: ['('], matched: 1
  • End: stack non-empty (1 unmatched gate). Return -1.

Trace: )(

  • Step 1: ) — stack is empty. Return -1 immediately.

The four traces cover the main failure modes: valid nested pairs, unmatched opening gate at end, and invalid closing gate at start.

Time and Space Complexity

VariantTimeSpace
StackO(n)O(n) worst case (all ()
CounterO(n)O(1)

Both make a single pass through the input. For Wipro’s coding test, either implementation is acceptable and will run within any reasonable time limit. In an interview conversation, the stack variant is worth explaining first because it shows you understand the general pattern, and the counter optimisation can be offered as a follow-up if the interviewer asks about space.

A common edge case to handle: the empty string. Both implementations return 0 for an empty input, which is correct (no gates, no matched pairs, system is safe by default). Testing this case before submission takes ten seconds and prevents an avoidable wrong answer.

A common mistake in coding tests is skipping the final stack-empty check. Returning count without the trailing if stack: return -1 produces wrong answers for inputs like ()(: the function would return 1 instead of -1. Both early-exit conditions matter: the unmatched ) check inside the loop, and the unmatched ( check after the loop. Missing either one fails around half of the standard test cases.

Wipro Placement Context

This problem appears in the Wipro NLTH (National Level Talent Hunt) coding module. The coding section runs 60 minutes and typically contains 2 to 3 problems; this question style, which tests stack-based pattern recognition, sits at the easier end of that set. A well-prepared student completes it in 20 to 25 minutes, leaving time for the harder problems.

Stack problems in Wipro’s coding round often appear alongside array manipulation and string processing questions. The gates problem is a useful warm-up for other stack-based patterns (next greater element, stock span, expression validation) that show up at slightly higher difficulty in the same 60-minute module. Practising the gates problem gives you the mental template for all of them: push, conditional pop, check after loop.

For the full breakdown of every NLTH module (aptitude, verbal, logical, and coding), see the Wipro NLTH pattern and syllabus. For more coding patterns that repeat across Wipro drives (array manipulation, string questions, mathematical problems), the Wipro coding questions collection covers the full range.

On hiring volumes: according to Wipro CHRO Saurabh Govil’s Q3 FY26 commentary, Wipro revised its FY26 fresher intake guidance down to 7,500–8,000 from an earlier target of 10,000–12,000. The company’s 50 university Centres of Excellence (co-building AI, cybersecurity, and data curriculum with universities) carry salary premiums over the standard Velocity/Standard track at ₹3.5–4.0 LPA per the same Q3 FY26 data. Fewer total slots makes the assessment filter more competitive, not less.

DSA fluency is the floor. It clears the NLTH coding module. Applied AI skills are what separate the standard hire (₹3.5–4.0 LPA Velocity track) from the CoE premium hire. If the coding round is already solid and the next investment is AI skills toward those CoE roles, TinkerLLM offers project-based LLM exercises at ₹299, a low-cost first step toward shipping an applied AI project.

For students preparing for Wipro and Accenture drives simultaneously, the technical and HR patterns overlap more than either company’s official material suggests. The Wipro and Accenture hot interview questions guide covers the shared patterns worth drilling before either drive.

Primary sources

Frequently asked questions

What does the function return for the input ()()?

It returns 2. There are two matched gate pairs, one for each () sequence. The counter increments once per matched pair.

What happens if a closing gate appears before any opening gate?

The function returns -1 immediately. A closing gate with no preceding opening gate means the system design is invalid and the sequence is unsafe.

Can this problem be solved without a stack?

Yes. For single-bracket input, a counter works: increment on `(` and decrement on `)`. If the counter goes negative at any point, return -1. If the counter is non-zero at the end, return -1. Otherwise return the total decrements.

Which round of Wipro placement includes this type of problem?

It appears in the Wipro NLTH coding section, typically a 60-minute module with 2 to 3 problems. This question type is usually solved in 20 to 25 minutes.

How does this differ from the standard balanced brackets problem?

The balanced brackets problem uses three types: (), [], and {}. The gates problem uses only parentheses and returns a count of matched pairs rather than a simple true or false answer.

What is the time and space complexity of the stack solution?

Time complexity is O(n), one pass through the input string. Space complexity is O(n) in the worst case. The counter variant reduces space to O(1).

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹299 launch)
Free AI Roadmap PDF