
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
Queries for Characters in a Repeated String in C++
In this problem, we are given a string str and Q queries consisting of two values a and b. Our task is to create a program to solve Queries for characters in a repeated string in C++.
Problem Description
To solve each query, we need to check whether the characters at index a and b are the same and return the value accordingly.
Let’s take an example to understand the problem,
Input: str = “tutorialspoint”
Q = 2
Query = {{0, 2}, {4, 7}}
Output:Repeated
Not Repeated
Explanation
For Query 1, the character at index 0 is t, and the character at index 2 is t. Both are the same characters.
For Query 1, the character at index 4 is r, and the character at index 7 is l. Both are not the same characters.
Solution Approach
To solve the problem, we will simply check for the equivalence of the elements at index a and b. If any index is greater than the length of string, be will find the value of (index%len), to get the character’s index. And the user the new index for comparison.
Example
#include <iostream> #include <string> using namespace std; bool isrepeated(string str, int len, int a, int b){ if(a > len) a %= len; if(b > len) b %= len; if(str[a] == str[b]) return true; else return false; } int main(){ string str = "tutorialspoint"; int len = str.length(); int Q = 3; int query[Q][2] = {{0, 2}, {3, 32}, {5, 18}}; for(int i = 0; i < Q; i++){ if(isrepeated(str, len, query[i][0], query[i][1])) cout<<"Character is repeated in both the index values"<<endl; else cout<<"Character is not repeated in both the index values"<<endl; } return 0; }
Output
Character is repeated in both the index values Character is not repeated in both the index values Character is not repeated in both the index values