Minimum Rotations to Unlock a Circular Lock

Last Updated : 14 Jul, 2026

Given two positive integers r and d of the same length, representing the current and desired lock configurations, respectively, where each digit corresponds to a circular ring numbered from 0 to 9, find the minimum number of rotations required to transform r into d.

  • In one operation, a ring can be rotated by one position either clockwise or anticlockwise.
  • The rings are circular, so 9 wraps to 0 and 0 wraps to 9.

Examples:  

Input: r = 222, d = 333
Output: 3
Explanation: Each digit 2 can be changed to 3 in one rotation. Therefore, the minimum total rotations required are 1 + 1 + 1 = 3.

Input: r = 2345, d = 5432
Output: 8
Explanation: The minimum rotations required for the corresponding digit pairs (2, 5), (3, 4), (4, 3), and (5, 2) are 3, 1, 1, and 3, respectively. Therefore, the minimum total rotations required are 3 + 1 + 1 + 3 = 8.

Try It Yourself
redirect icon

[Naive Approach] Digit by Digit Simulation - O(n * 10) Time and O(n) Space

The idea is to process each corresponding digit of r and d independently. For every pair of digits, simulate both clockwise and anticlockwise rotations one step at a time until the target digit is reached. Add the smaller number of rotations for each digit to the final answer.

Working of Approach:

  • Traverse each corresponding digit of r and d, and simulate both clockwise and anticlockwise rotations until the target digit is reached.
  • Count the rotations in both directions, choose the smaller count, and add it to the answer.
  • Repeat this process for all digits and return the total minimum rotations.
C++
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;

int rotationCount(int r, int d)
{

    // Convert numbers into strings.
    string s1 = to_string(r);
    string s2 = to_string(d);

    // Pad the shorter string with leading zeros.
    while (s1.size() < s2.size())
        s1 = "0" + s1;

    while (s2.size() < s1.size())
        s2 = "0" + s2;

    int ans = 0;

    // Process every digit.
    for (int i = 0; i < s1.size(); i++)
    {

        int a = s1[i] - '0';
        int b = s2[i] - '0';

        // Simulate clockwise rotation.
        int cw = 0;
        int cur = a;
        while (cur != b)
        {
            cur = (cur + 1) % 10;
            cw++;
        }

        // Simulate anticlockwise rotation.
        int ccw = 0;
        cur = a;
        while (cur != b)
        {
            cur = (cur + 9) % 10;
            ccw++;
        }

        ans += min(cw, ccw);
    }

    return ans;
}

int main()
{
    int r = 2345, d = 5432;

    cout << rotationCount(r, d);

    return 0;
}
Java
import java.util.*;

class GFG {

    static int rotationCount(int r, int d)
    {

        // Convert numbers into strings.
        String s1 = Integer.toString(r);
        String s2 = Integer.toString(d);

        // Pad the shorter string with leading zeros.
        while (s1.length() < s2.length())
            s1 = "0" + s1;

        while (s2.length() < s1.length())
            s2 = "0" + s2;

        int ans = 0;

        // Process every digit.
        for (int i = 0; i < s1.length(); i++) {

            int a = s1.charAt(i) - '0';
            int b = s2.charAt(i) - '0';

            // Simulate clockwise rotation.
            int cw = 0;
            int cur = a;
            while (cur != b) {
                cur = (cur + 1) % 10;
                cw++;
            }

            // Simulate anticlockwise rotation.
            int ccw = 0;
            cur = a;
            while (cur != b) {
                cur = (cur + 9) % 10;
                ccw++;
            }

            ans += Math.min(cw, ccw);
        }

        return ans;
    }

    public static void main(String[] args)
    {

        int r = 2345, d = 5432;

        System.out.println(rotationCount(r, d));
    }
}
Python
def rotationCount(r, d):

    # Convert numbers into strings.
    s1 = str(r)
    s2 = str(d)

    # Pad the shorter string with leading zeros.
    s1 = s1.zfill(max(len(s1), len(s2)))
    s2 = s2.zfill(max(len(s1), len(s2)))

    ans = 0

    # Process every digit.
    for i in range(len(s1)):

        a = int(s1[i])
        b = int(s2[i])

        # Simulate clockwise rotation.
        cw = 0
        cur = a
        while cur != b:
            cur = (cur + 1) % 10
            cw += 1

        # Simulate anticlockwise rotation.
        ccw = 0
        cur = a
        while cur != b:
            cur = (cur + 9) % 10
            ccw += 1

        ans += min(cw, ccw)

    return ans


if __name__ == "__main__":
    r = 2345
    d = 5432

    print(rotationCount(r, d))
C#
using System;

class GFG {

    static int rotationCount(int r, int d)
    {

        // Convert numbers into strings.
        string s1 = r.ToString();
        string s2 = d.ToString();

        // Pad the shorter string with leading zeros.
        s1 = s1.PadLeft(Math.Max(s1.Length, s2.Length),
                        '0');
        s2 = s2.PadLeft(Math.Max(s1.Length, s2.Length),
                        '0');

        int ans = 0;

        // Process every digit.
        for (int i = 0; i < s1.Length; i++) {

            int a = s1[i] - '0';
            int b = s2[i] - '0';

            // Simulate clockwise rotation.
            int cw = 0;
            int cur = a;
            while (cur != b) {
                cur = (cur + 1) % 10;
                cw++;
            }

            // Simulate anticlockwise rotation.
            int ccw = 0;
            cur = a;
            while (cur != b) {
                cur = (cur + 9) % 10;
                ccw++;
            }

            ans += Math.Min(cw, ccw);
        }

        return ans;
    }

    static void Main()
    {

        int r = 2345, d = 5432;

        Console.WriteLine(rotationCount(r, d));
    }
}
JavaScript
function rotationCount(r, d)
{

    // Convert numbers into strings.
    let s1 = r.toString();
    let s2 = d.toString();

    let ans = 0;

    // Process every digit.
    for (let i = 0; i < s1.length; i++) {

        let a = parseInt(s1[i]);
        let b = parseInt(s2[i]);

        // Simulate clockwise rotation.
        let cw = 0;
        let cur = a;
        while (cur != b) {
            cur = (cur + 1) % 10;
            cw++;
        }

        // Simulate anticlockwise rotation.
        let ccw = 0;
        cur = a;
        while (cur != b) {
            cur = (cur + 9) % 10;
            ccw++;
        }

        ans += Math.min(cw, ccw);
    }

    return ans;
}

//Driver Code
let r = 2345;
let d = 5432;

console.log(rotationCount(r, d));

Output
8

[Expected Approach] Using Digit Extraction - O(n) Time and O(1) Space

The idea is to extract each digit using modulo (% 10), compute the direct and circular rotation distances, add the smaller one to the answer, and repeat until all digits are processed.

For a single ring, we can rotate it in either of two directions:
0 -> 1 -> 2 -> ... -> 9 -> 0
0 <- 9 <- 8 <- ... <- 1 <- 0

If a ring needs to rotate from digit a to digit b, moving directly requires abs(a - b) rotations, while moving in the opposite direction requires 10 - abs(a - b) rotations because the digits are arranged in a circle. Therefore, the minimum rotations required for one ring are: min(abs(a - b), 10 - abs(a - b)).

Each ring is independent of the others, so we compute this minimum cost for every corresponding pair of digits and sum the results. Starting from the rightmost digit, we repeatedly extract digits using % 10, calculate the minimum rotations, and move to the next digit by dividing the numbers by 10.

Let us understand with an example:

  • Consider r = 2345 and d = 5432. Start comparing digits from the rightmost side.
  • Compare (5, 2): diff = 3, circular distance = 7, so add 3. Total = 3.
  • Compare (4, 3) and (3, 4): for both pairs, diff = 1, so add 1 + 1. Total = 5.
  • Compare (2, 5): diff = 3, circular distance = 7, so add 3. Total = 8.
  • All digits are processed, so the minimum rotations required are 8.
C++
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;

int rotationCount(int r, int d)
{
    int res = 0;

    while (r > 0 || d > 0)
    {

        // Add the minimum rotations needed for the current digit.
        int diff = abs((r % 10) - (d % 10));
        res += min(diff, 10 - diff);
        r /= 10;
        d /= 10;
    }

    return res;
}

int main()
{
    int r = 2345, d = 5432;

    cout << rotationCount(r, d);

    return 0;
}
Java
import java.util.*;

class GFG {

    static int rotationCount(int r, int d)
    {
        int res = 0;

        while (r > 0 || d > 0) {

            // Add the minimum rotations needed for the
            // current digit.
            int diff = Math.abs((r % 10) - (d % 10));
            res += Math.min(diff, 10 - diff);
            r /= 10;
            d /= 10;
        }

        return res;
    }

    public static void main(String[] args)
    {
        int r = 2345, d = 5432;

        System.out.println(rotationCount(r, d));
    }
}
Python
def rotationCount(r, d):
    res = 0

    while r > 0 or d > 0:

        # Add the minimum rotations needed for the current digit.
        diff = abs((r % 10) - (d % 10))
        res += min(diff, 10 - diff)
        r //= 10
        d //= 10

    return res


if __name__ == "__main__":
    r = 2345
    d = 5432

    print(rotationCount(r, d))
C#
using System;

class GFG {

    static int rotationCount(int r, int d)
    {
        int res = 0;

        while (r > 0 || d > 0) {

            // Add the minimum rotations needed for the
            // current digit.
            int diff = Math.Abs((r % 10) - (d % 10));
            res += Math.Min(diff, 10 - diff);
            r /= 10;
            d /= 10;
        }

        return res;
    }

    static void Main()
    {
        int r = 2345, d = 5432;

        Console.WriteLine(rotationCount(r, d));
    }
}
JavaScript
function rotationCount(r, d)
{
    let res = 0;

    while (r > 0 || d > 0) {

        // Add the minimum rotations needed for the current
        // digit.
        let diff = Math.abs((r % 10) - (d % 10));
        res += Math.min(diff, 10 - diff);
        r = Math.floor(r / 10);
        d = Math.floor(d / 10);
    }

    return res;
}

// Driver Code
let r = 2345;
let d = 5432;

console.log(rotationCount(r, d));

Output
8
Comment