VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-of-digits-in-n-and-m-that-are-same-but-present-on-different-indices/

⇱ Count of digits in N and M that are same but present on different indices - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count of digits in N and M that are same but present on different indices

Last Updated : 9 Feb, 2022

Given two numbers N and M, the task is to find the count of digits in N and M that are the same but present on different indices.

Examples:

Input: N = 123, M = 321
Output: 2
Explanation: Digit 1 and 3 satisfies the condition

Input: N = 123, M = 111
Output: 0

Approach: The problem can be solved using hashing and two-pointer approach.

  • Convert N and M to string for ease of traversal
  • Now create 2 hash of size 10 to store frequency of digits in N and M respectively
  • Now traverse a loop from 0-9 and:
    • Add min of hashN[i] and hashM[i] to a variable count
  • Now traverse the numbers using two pointers to find the count of digits that are same and occur on same indices in both N and M. Store the count in variable same_dig_cnt
  • Now return the final count as count - same_dig_cnt

Below is the implementation of the above approach:

 
 


Output
2


 

Time Complexity: O(D), where D is the max count of digits in N or M
Auxiliary Space: O(D), where D is the max count of digits in N or M


 

Comment
Article Tags: