← Infosys bank

Infosys · Question 66 · Queues

Open the Lock

QueuesC++code⏱ O(10^4)💾 O(10^4)
Service-based

Problem

Minimum moves to open a lock with deadends and target using BFS.

Approach

BFS through possible states avoiding deadends.

Time O(10^4)Space O(10^4)

How it works

  1. 1BFS over 4-wheel states level by level.
  2. 2Skip deadends and visited states.

Sample input / output

Input:
deadends = ["0201","0101","0102","1212","2002"], target = "0202"
Output:
6

Constraints

1 <= deadends.length <= 500; 4-digit strings.

Solution — read it, then walk it

Time O(10^4)Space O(10^4)Loops 3Branches 5Returns 2source · C++
Scroll sideways for wide charts — the view follows the active step.
↻ repeatyesnoyes↻ repeat↻ repeat↻ repeatSTARTinclude <iostream>include <string>include <vector>include <unordered_set>include <queue>using namespace stdCLASS SolutionDEFINEDEFINEopenLock(vector<string>&deadends, string target)unordered_set<string>dead(deadends.begin(),deadends.end())if(dead.count("0000"))return -1queue<string> qunordered_set<string>visitedq.push("0000")visited.insert("0000")DEFINE steps = 0while (!q.empty())DEFINE size = q.size()while (size--)DEFINE curr = q.front()q.pop()if (curr == target)return stepsif (dead.count(curr))continuefor (int i = 0; i < 4;i++)DEFINE up = curr, down =currup[i] = (curr[i] == '9') ?'0' : curr[i] + 1down[i] = (curr[i] == '0')? '9' : curr[i] - 1if(!visited.count(up))visited.insert(up)q.push(up)if(!visited.count(down))visited.insert(down)q.push(down)steps++RETURN -1DEFINE main()Solution solvector<string> dead ={"0201","0101","0102","1212","2002"}cout << sol.openLock(dead,"0202") << endlRETURN 0END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/41

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits