algoadvance

Leetcode 2843. Count Symmetric Integers

Problem Statement

You are given two integers, low and high. A symmetric integer is an integer that reads the same both forward and backward (i.e., a palindrome). Your task is to count the number of symmetric integers between low and high, inclusive.

For example, if low is 10 and high is 150, there are several symmetric integers such as 11, 22, etc., up to 121.

Clarifying Questions

  1. Range of inputs:
    • What are the constraints on low and high?
    • Are the values of low and high guaranteed to be non-negative and non-zero?
  2. Edge cases:
    • What happens if low is equal to high?
    • Do we need to consider single-digit numbers as symmetric integers?

Plan

  1. Iterate through each number: Iterate through each number from low to high.
  2. Check for symmetry: For each number, convert it to a string and check if it is a palindrome.
  3. Count symmetric integers: Maintain a counter to count all the symmetric integers.

Strategy

  1. Use a loop to iterate from low to high.
  2. Convert each number to a string.
  3. Check if the string is the same forwards and backwards.
  4. If a number is symmetric, increment the counter.
  5. Return the counter after the loop ends.

Time Complexity

Code

#include <iostream>
#include <string>

class Solution {
public:
    int countSymmetricIntegers(int low, int high) {
        int count = 0;
        for (int i = low; i <= high; ++i) {
            if (isSymmetric(i)) {
                count++;
            }
        }
        return count;
    }

private:
    bool isSymmetric(int num) {
        std::string s = std::to_string(num);
        int left = 0;
        int right = s.size() - 1;
        
        while (left < right) {
            if (s[left] != s[right]) {
                return false;
            }
            left++;
            right--;
        }
        
        return true;
    }
};

int main() {
    Solution sol;
    int low = 10;
    int high = 150;
    std::cout << "Number of symmetric integers: " << sol.countSymmetricIntegers(low, high) << std::endl;
    return 0;
}

Explanation of the Code

  1. Class Definition: We define a class Solution with two member functions.
  2. countSymmetricIntegers: This method iterates from low to high and uses the isSymmetric helper method to check if a number is a palindrome. It keeps a count of symmetric integers.
  3. isSymmetric: This helper method converts an integer to a string and checks if the string is a palindrome by comparing characters from the start and end moving towards the center.
  4. Main Function: We instantiate the Solution class and call the countSymmetricIntegers method with the sample low and high values, then print the result.

This solution ensures all numbers in the given range are checked, and only the symmetric ones are counted.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI