LeetCode 246: Strobogrammatic Number Solution

Master LeetCode problem 246 (Strobogrammatic Number), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

246. Strobogrammatic Number

Problem Explanation

Explanation

To solve this problem, we need to determine whether a given number is a strobogrammatic number. A strobogrammatic number is a number that looks the same when rotated 180 degrees.

We can create a mapping of valid strobogrammatic pairs: (0,0), (1,1), (6,9), (8,8), (9,6).

We iterate through the number from the start and end simultaneously, checking if the pair of digits at each position is a valid strobogrammatic pair. If they are not, we return false. If all pairs are valid, we return true.

Time complexity: O(N) where N is the number of digits in the input number. Space complexity: O(1)

Solution Code

class Solution {
    public boolean isStrobogrammatic(String num) {
        int left = 0, right = num.length()-1;
        while (left <= right) {
            if (!isValid(num.charAt(left), num.charAt(right))) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
    
    private boolean isValid(char c1, char c2) {
        return (c1 == '0' && c2 == '0') || (c1 == '1' && c2 == '1') || (c1 == '6' && c2 == '9') || (c1 == '8' && c2 == '8') || (c1 == '9' && c2 == '6');
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 246 (Strobogrammatic Number)?

This page provides optimized solutions for LeetCode problem 246 (Strobogrammatic Number) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 246 (Strobogrammatic Number)?

The time complexity for LeetCode 246 (Strobogrammatic Number) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 246 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 246 in Java, C++, or Python.

Back to LeetCode Solutions