
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Number of Calling Person Pairs in C++
Suppose we have an array A with n elements. A[i] determines the ith id. A[i] is the number of SKP call session. If A[i] is 0, it indicates the person is not using SKP calling system. We have to analyze these data and find out the number of pairs of calling person that are talking. If this is not possible, return -1.
Problem Category
This problem falls under sorting problems. Sorting is a very common problem while we are talking about different problem-solving algorithms in computer science. As the name suggests, sorting indicates arranging a set of data into some fashion. We can arrange them in nondecreasing order or non-increasing order in general. Otherwise sorting can be also takes place in a pre-defined manner. For the string-based problems, sometimes we refer lexicographical sorting to arrange letters in dictionary fashion. There are plenty of different sorting techniques with certain variations and their time and space complexity. To date, the lower-bound of the time complexity for comparison-based sorting techniques is O(n*log n). However, there are some mechanical sorting techniques like bucket sort, radix sort, counting sorts are there whose time complexity is linear O(n) in time. For further reading, please follow the link below −
So, if the input of our problem is like A = [0, 1, 7, 1, 7, 10], then the output will be 2, because there are two SKP calls between the call persons: the person 2 and person 4, person 3 and person 5.
Steps
To solve this, we will follow these steps −
t := 0 ans := 0 n := size of A sort the array A for initialize i := 0, when i < n - 1, update (increase i by 1), do: if A[i] is same as A[i + 1] and A[i] is not equal to 0, then: (increase t by 1) (increase ans by 1) if t >= 2, then: return -1 Otherwise t := 0 return ans
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; int solve(vector<int> A){ int t = 0; int ans = 0; int n = A.size(); sort(A.begin(), A.end()); for (int i = 0; i < n - 1; i++){ if (A[i] == A[i + 1] && A[i] != 0){ t++; ans++; if (t >= 2){ return -1; } } else t = 0; } return ans; } int main(){ vector<int> A = { 0, 1, 7, 1, 7, 10 }; cout << solve(A) << endl; }
Input
{ 0, 1, 7, 1, 7, 10 }
Output
2