C++ Program to find length of country code from phone numbers


Suppose we have a list of strings S with n numeric strings. Amal has n friends in a city. Amal knows phone numbers of all his friends: they are stored in S. All strings in S are of same length. Once Amal needed to figure out the city phone code. He assumed that the phone code of the city is the longest common prefix of all phone numbers of his friends. We have to find the length of the city phone code.

Problem Category

To solve this problem, we need to manipulate strings. Strings in a programming language are a stream of characters that are stored in a particular array-like data type. Several languages specify strings as a specific data type (eg. Java, C++, Python); and several other languages specify strings as a character array (eg. C). Strings are instrumental in programming as they often are the preferred data type in various applications and are used as the datatype for input and output. There are various string operations, such as string searching, substring generation, string stripping operations, string translation operations, string replacement operations, string reverse operations, and much more. Check out the links below to understand how strings can be used in C/C++.

https://www.tutorialspoint.com/cplusplus/cpp_strings.htm

https://www.tutorialspoint.com/cprogramming/c_strings.htm

So, if the input of our problem is like S = ["00209", "00219", "00999", "00909"], then the output will be 2, because the code is "00"

Steps

To solve this, we will follow these steps −

n := size of S
ans := 0
m := size of S[0]
for initialize i := 0, when i < m, update (increase i by 1), do:
   c := S[0, i]
   for initialize j := 0, when j < n, update (increase j by 1), do:
      if S[j, i] is not equal to c, then:
         return ans
   (increase ans by 1)
return ans

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(vector<string> S){
   int n = S.size();
   int ans = 0;
   int m = S[0].size();
   for (int i = 0; i < m; i++){
      char c = S[0][i];
      for (int j = 0; j < n; j++){
         if (S[j][i] != c){
            return ans;
         }
      }
      ans++;
   }
   return ans;
}
int main(){
   vector<string> S = { "00209", "00219", "00999", "00909" };
   cout << solve(S) << endl;
}

Input

{ "00209", "00219", "00999", "00909" }

Output

2

Updated on: 07-Apr-2022

411 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements