Strings
Reverse Words in a String
Mark as Completed
240
Problem Statement: Given a string s, reverse the words of the string.
Examples:
Example 1:
Input: s=”this is an amazing program”
Output: “program amazing an is this”
Example 2:
Input: s=”This is decent”
Output: “decent is This”
Brute force
#include<bits/stdc++.h>
using namespace std;
int main()
string s="TUF is great for interview preparation";
cout<<"Before reversing words: "<<endl;
cout<<s<<endl;
s+=" ";
stack<string> st;
int i;
string str="";
for(i=0;i<s.length();i++)
{
if(s[i]==' ')
st.push(str);
str="";
else str+=s[i];
string ans="";
while(st.size()!=1)
ans+=st.top()+" ";
st.pop();
ans+=st.top();// The last word should'nt have a space after it
cout<<"After reversing words: "<<endl;
cout<<ans;
return 0;
#include<bits/stdc++.h>
using namespace std;
string result(string s)
int left = 0;
int right = s.length()-1;
string temp="";
string ans="";
//Iterate the string and keep on adding to form a word
//If empty space is encountered then add the current word to the result
while (left <= right) {
char ch= s[left];
if (ch != ' ') {
temp += ch;
} else if (ch == ' ') {
if (ans!="") ans = temp + " " + ans;
else ans = temp;
temp = "";
left++;
//If not empty string then add to the result(Last word is added)
if (temp!="") {
if (ans!="") ans = temp + " " + ans;
else ans = temp;
return ans;
int main()
string st="TUF is great for interview preparation";
cout<<"Before reversing words: "<<endl;
cout<<st<<endl;
cout<<"After reversing words: "<<endl;
cout<<result(st);
return 0;
Output:
Before reversing words:
TUF is great for interview preparation
After reversing words:
preparation interview for great is TUF
Time Complexity: O(N), N~length of string
Space Complexity: O(1), Constant Space
Longest common prefix
Example 1:
Input: strs = ["flower","flow","flight"]
Output: "fl"
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.empty()){
return "";
string prefix=strs[0];
for(string s:strs){
while(s.find(prefix)!=0){
prefix=prefix.substr(0,prefix.size()-1);
}
}
return prefix;
};
Check if two Strings are anagrams of each other
Mark as Completed
99
Problem Statement: Given two strings, check if two strings are anagrams of each other or
not.
Examples:
Example 1:
Input: CAT, ACT
Output: true
Explanation: Since the count of every letter of both strings are equal.
Example 2:
Input: RULES, LESRT
Output: false
Explanation: Since the count of U and T is not equal in both strings.
BRUTE FORCE
#include <iostream>
#include <algorithm>
using namespace std;
bool CheckAnagrams(string str1, string str2)
// Case 1: when both of the strings have different lengths
if (str1.length() != str2.length())
return false;
sort(str1.begin(), str1.end());
sort(str2.begin(), str2.end());
// Case 2: check if every character of str1 and str2 matches with each other
for (int i = 0; i < str1.length(); i++)
if (str1[i] != str2[i])
return false;
return true;
int main()
string Str1 = "INTEGER";
string Str2 = "TEGERNI";
if(CheckAnagrams(Str1, Str2))
cout << "True" << endl;
else
cout<<"False"<<endl;
return 0;
Optimal
#include <iostream>
#include <algorithm>
using namespace std;
bool CheckAnagrams(string str1, string str2)
{
// when both of the strings have different lengths
if (str1.length() != str2.length())
return false;
int freq[26] = {0};
for (int i = 0; i < str1.length(); i++)
freq[str1[i] - 'A']++;
for (int i = 0; i < str2.length(); i++)
freq[str2[i] - 'A']--;
for (int i = 0; i < 26; i++)
if (freq[i] != 0)
return false;
return true;
int main()
string Str1 = "INTEGER";
string Str2 = "TEGERNI";
if(CheckAnagrams(Str1, Str2))
cout << "True" << endl;
else
cout<<"False"<<endl;
return 0;
Output: True
Time Complexity: O(n) where n is the length of string
Space Complexity: O(1)
3)sort characters by frequency
Example 1:
Input: s = "tree"
Output: "eert"
Explanation: 'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
class Solution {
public:
string frequencySort(string s) {
unordered_map<char,int>mpp;
for(auto ch: s){
mpp[ch]++;
vector<pair<int,char>>freqvec;
for(auto it:mpp){
freqvec.push_back({it.second,it.first});
sort(freqvec.rbegin(),freqvec.rend());
string result;
for(auto it:freqvec){
result.append(it.first,it.second);
return result;
};
Roman to integer
Example 1:
Input: s = "III"
Output: 3
Explanation: III = 3.
Example 2:
Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
class Solution {
public:
int romanToInt(string s) {
unordered_map<char,int>mp;
mp['I']=1;
mp['V']=5;
mp['X']=10;
mp['L']=50;
mp['C']=100;
mp['D']=500;
mp['M']=1000;
int ans=0;
for(int i=0;i<s.size();i++){
if(mp[s[i]]<mp[s[i+1]]){
ans=ans-mp[s[i]];
else{
ans=ans+mp[s[i]];
return ans;
};
4)String to atoi
Input: s = "42"
Output: 42
Explanation:
The underlined characters are what is read in and the caret is the current reader position.
Step 1: "42" (no characters read because there is no leading whitespace)
Step 2: "42" (no characters read because there is neither a '-' nor '+')
^
Step 3: "42" ("42" is read in)
Example 2:
Input: s = " -042"
Output: -42
Explanation:
Step 1: " -042" (leading whitespace is read and ignored)
Step 2: " -042" ('-' is read, so the result should be negative)
Step 3: " -042" ("042" is read in, leading zeros ignored in the result)
class Solution {
public:
int myAtoi(string s) {
int i=0;
int sign=1;
long ans=0;
while(i<s.length() && s[i]==' '){
i++;
if(s[i]=='-'){
sign=-1;
i++;
else if(s[i]=='+'){
i++;
}
while(i<s.length()){
if(s[i]>='0'&& s[i]<='9'){
ans=ans*10+(s[i]-'0');
if(ans>INT_MAX && sign==-1){
return INT_MIN;
else if(ans>INT_MAX && sign==1){
return INT_MAX;
i++;
else{
return ans*sign;
return (ans*sign);
};