Android Unlock Patterns - Problem

Android devices feature a unique security system: a 3x3 grid of dots that users connect to create unlock patterns. Imagine drawing lines between numbered dots (1-9) where each line segment connects two consecutive dots in your sequence.

The challenge? Not all connections are valid! Here are the rules:

  • All dots must be unique - you can't use the same dot twice
  • No jumping through unvisited dots - if your line passes through the center of another dot, that dot must have been visited earlier

For example:

1 2 3
4 5 6
7 8 9

Invalid: [4,1,3,6] - connecting 1→3 passes through dot 2, but 2 wasn't visited first
Valid: [2,4,1,3,6] - now 1→3 is allowed because 2 was visited earlier

Your mission: Given integers m and n, count all unique valid unlock patterns with length between m and n dots (inclusive).

Input & Output

example_1.py — Basic Range
$ Input: m = 1, n = 1
Output: 9
💡 Note: All single-dot patterns are valid: [1], [2], [3], [4], [5], [6], [7], [8], [9]. Each dot can be a valid pattern of length 1.
example_2.py — Small Range
$ Input: m = 1, n = 2
Output: 65
💡 Note: Includes all 9 single-dot patterns plus all valid 2-dot patterns. From each dot, you can move to any other dot except those that require jumping through unvisited intermediate dots.
example_3.py — Edge Case
$ Input: m = 3, n = 3
Output: 320
💡 Note: Only counts patterns of exactly length 3. Many more possibilities exist since by length 3, intermediate dots for jumps are more likely to have been visited.

Constraints

  • 1 ≤ m ≤ n ≤ 9
  • Grid is always 3×3 with dots numbered 1-9
  • Jump Rule: Cannot connect two dots if line passes through center of unvisited dot

Visualization

Tap to expand
Android Unlock Patterns - DFS Approach INPUT 1 2 3 4 5 6 7 8 9 m = 1 n = 1 Pattern length: 1 to 1 Single dot patterns only ALGORITHM STEPS 1 Define Skip Map Track which dots must be visited between jumps 2 DFS from each dot Start DFS from dots 1-9 Mark visited, explore 3 Validate Moves Check if skip dot is visited (if required) 4 Count Valid Paths When length in [m,n], increment counter Symmetry Optimization: Corners (1,3,7,9): same count Edges (2,4,6,8): same count Center (5): unique count FINAL RESULT 1 2 3 4 5 6 7 8 9 Each dot = 1 valid pattern Output: 9 OK - 9 single-dot patterns All dots valid for length 1 Key Insight: The skip map defines which intermediate dots must be visited before making diagonal/straight jumps. For example: 1-->3 requires 2 visited, 1-->9 requires 5 visited. Use symmetry to optimize: Total = 4 * DFS(corner) + 4 * DFS(edge) + DFS(center). Time: O(n!), Space: O(n) for recursion. TutorialsPoint - Android Unlock Patterns | DFS Approach
Asked in
Google 45 Amazon 32 Meta 28 Apple 25
52.4K Views
Medium Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen