String Medium Coding
String Medium Coding
Difficulty:medium
Q1. You have write a function that accepts, a string which length is “len”, the string
has some “#”, in it you have to move all the hashes to the front of the string and
return the whole string back and print it.
example :-
Input:
Move#Hash#to#Front
Output:
###MoveHashtoFront
solution -:
• C++ solution
#include <iostream>
#include <cstring>
using namespace std;
str1[j] = '\0';
str2[k] = '\0';
strcat(str1, str2);
cout << str1 << endl; // Output the result
return str1;
}
int main() {
char a[100];
cin >> a; // Input string
import [Link];
[Link](moveHash(input));
[Link]();
}
}
Q2. Given an integer N, find its factorial. return a list of integers denoting the digits
that make up the factorial of N.
Example
Input: N = 5
Output: [1,2,0]
Explanation : 5! = 1*2*3*4*5 = 120
Input: N = 10
Output: [3,6,2,8,8,0,0]
Explanation :
10! = 1*2*3*4*5*6*7*8*9*10 = 3628800
Your Task:
You don't need to read input or print anything. Complete the function factorial() that takes
integer N as input parameter and returns a list of integers denoting the digits that make up
the factorial of N.
solution -:
• C++ solution
class Solution{
public:
void multiply(int n, vector<int>& number) {
int carry = 0;
for (int i = 0; i < [Link](); i++) {
int num = n * number[i];
number[i] = (char)((num + carry) % 10);
carry = (num + carry) / 10;
}
while (carry) {
number.push_back(carry % 10);
carry /= 10;
}
}
vector<int> factorial(int N){
vector<int> number;
number.push_back(1);
for (int i = 2; i <= N; i++)
multiply(i, number);
reverse([Link](), [Link]());
return number;
}
};
• Java solution
class Solution {
[Link](number);
return number;
}
Difficulty:medium
Q3-You are given a string S of length N. Your task is to find the index(considering 1-
based indexing) of the first unique character present in the string. If there are no
unique characters return -1.
Note
A unique character in a string is the character that appears only once in the string. For
example, ‘h’, ‘e’, and ‘o’ are the unique characters in the string “hello” .
The first line of each test case contains a positive integer N, which represents the length of the
string.
Sample Input 1 :
2
16
codingninjascode
24
practicepracticepractice
Sample Output 1:
6
-1
Explanation for Input 1:
For the first subtask the explanation is given in the problem statement.
For the second subtask there are no unique characters so ans is -1.
Sample Input 2 :
3
19
palindromemordnilap
9
notunique
7
caaabbc
Sample Output 2:
10
2
-1
Explanation for Input 2:
For the first subtask, every character except ‘e’ occurs 2 times so we print the index of e that is
10.
For the second subtask, the characters ‘o’ , ‘t’ , ‘e’ , ‘i’ and ‘q’ are unique but ‘o’ occurs before
all the other unique characters .
For the third subtask, all the characters are not unique so we return -1.
solution -:
• C++ solution
if(unique == true) {
return i+1;
}
}
return -1.
return -1;
}
• Java solution
if (unique == true) {
return i + 1;
}
return -1;
}
Q4. Given a String. Reverse each word in it where the words are separated by dots.
Example
Input: S = "[Link]"
Output: [Link]
Explanation: The words are reversed as follows:"i" -> "i","like"->"ekil",
"this"->"siht","program" -> "margorp", "very" -> "yrev","much" -> "hcum".
Input: S = "[Link]"
Output: [Link]
Explanation: The words are reversed as follows:"pqr" -> "rqp" , "mno" -> "onm"
Your Task:
You don't need to read input or print anything. Your task is to complete the
functionreverseWords()which takes the string S as input and returns the resultant string by
reversing all the words separated by dots.
Constraints:
1<=|S|<=10^5
solution -:
• C++ solution
#include<bits/stdc++.h>
using namespace std;
stringstream iss(str);
int main()
{
string s = "GeeksforGeeks is good to learn";
printWords(s);
return 0;
}
• Java solution
import [Link];
import [Link];
[Link](result);
String to Integer
Difficulty:medium
Ask By Company -:
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)
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)
Input: s = "1337c0d3"
Output: 1337
Explanation:
Step 1: "1337c0d3" (no characters read because there is no leading whitespace)
^
Step 2: "1337c0d3" (no characters read because there is neither a '-' nor '+')
^
Step 3: "1337c0d3" ("1337" is read in; reading stops because the next character
is a non-digit)
Input: s = "0-1"
Output: 0
Explanation:
Step 1: "0-1" (no characters read because there is no leading whitespace)
^
Step 2: "0-1" (no characters read because there is neither a '-' nor '+')
^
Step 3: "0-1" ("0" is read in; reading stops because the next character is a
non-digit)
Input: s = "words and 987"
Output: 0
Explanation:
Constraints:
solution -:
• C++ solution
class Solution {
public:
int myAtoi(string s)
{
int i=0;
int sign=1;
long ans=0;
while(i<[Link]() && s[i]==' ')
i++;
if(s[i]=='-')
{
sign=-1;
i++;
}
else if(s[i]=='+')
i++;
while(i<[Link]())
{
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);
}
};
• Java solution
class Solution {
public:
int myAtoi(string s) {
const int len = [Link]();
if(len == 0){
return 0;
}
int index = 0;
if(s[index] == '-'){
isNegative = true;
++index;
} else if (s[index] == '+'){
++index;
}
int result = 0;
if(result > (INT_MAX / 10) || (result == (INT_MAX / 10) && digit > 7)){
return isNegative ? INT_MIN : INT_MAX;
}
++index;
}
private:
bool isDigit(char ch){
return ch >= '0' && ch <= '9';
}
};
Difficulty:medium
Q6. Given an integer N, find its factorial. return a list of integers denoting the digits
that make up the factorial of N.
For Example:
Input: N = 5
Output: [1,2,0]
Explanation : 5! = 1*2*3*4*5 = 120
Input: N = 10
Output: [3,6,2,8,8,0,0]
Your Task:
You don't need to read input or print anything. Complete the function factorial() that takes
integer N as input parameter and returns a list of integers denoting the digits that make up
the factorial of N.
Constraints:
1 ≤ N ≤ 1000
solution -:
• C++ solution
class Solution{
public:
void multiply(int n, vector<int>& number) {
int carry = 0;
for (int i = 0; i < [Link](); i++) {
int num = n * number[i];
number[i] = (char)((num + carry) % 10);
carry = (num + carry) / 10;
}
while (carry) {
number.push_back(carry % 10);
carry /= 10;
}
}
reverse([Link](), [Link]());
return number;
}
};
• Java solution
class Solution {
[Link](number);
return number;
}
Ask By Company -:
Q7. You are given a string S of 2*N characters consisting of N ‘[‘ brackets and N ‘]’
brackets. A string is considered balanced if it can be represented in the
form S2[S1] where S1 and S2 are balanced strings. We can make an unbalanced
string balanced by swapping adjacent characters.
Calculate the minimum number of swaps necessary to make a string balanced.
Note - Strings S1 and S2 can be empty.
Example
Input : []][][
Output : 2
Explanation : First swap: Position 3 and 4 [][]][
Second swap: Position 5 and 6 [][][]
Input : c
Output : 0
Explanation: String is already balanced.
Your Task:
You don't need to read input or print anything. Your task is to complete the
function minimumNumberOfSwaps() which takes the string S and return minimum number
of operations required to balance the bracket sequence.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1<=|S|<=100000
solution -:
• C++ solution
class Solution{
public:
int minimumNumberOfSwaps(string S){
int swap=0, imbalance=0;
int countLeft=0, countRight=0;
int sizeOfArray=[Link]();
for(int i=0;i<sizeOfArray;++i){
if(S[i] == '[')
{
// increment count of Left bracket
countLeft++;
if(imbalance > 0)
{
swap += imbalance;
imbalance--;
}
}
else if(S[i] == ']' )
{
imbalance = (countRight-countLeft);
}
}
return swap;
}
};
• Java solution
return swap;
}
}
Rotate string
Difficulty:medium
Ask By Company -:
Q8. Given two strings s and goal , return true if and only if s can
become goal after some number of shifts on s .
Constraints:
• 1 <= [Link], [Link] <= 100
• s and goal consist of lowercase English letters.
solution -:
• C++ solution
class Solution {
public:
bool rotateString(string s, string goal) {
int n=[Link]();
int m=[Link]();
int i=0;
if(m!=n){
return false;
}
while(i<n){
if(s==goal){
return true;
}
char a=s[0];
for(int j=0;j<n-1;j++){
s[j]=s[j+1];
}
s[n-1]=a;
i++;
}
return false;
}
};
• Java solution
class Solution {
public boolean rotateString(String s, String goal) {
if([Link]() != [Link]()) return false;
s += s;
return [Link](goal);
}
}
Difficulty:medium
Q9. Given a string s containing 0's and 1's. You have to return the smallest positive
integer C, such that the binary string can be cut into C pieces and each piece should
be of the power of 5 with no leading zeros.
Note: The string s is a binary string. And if no such cuts are possible, then return -1.
Example:
Input: s = "101101101"
Output: 3
Explanation: We can split the given string into three 101s, where 101 is the binary
representation of 5.
Input: s = "00000"
Output: - 1
Explanation: 0 is not a power of 5.
Your Task:
Your task is to complete the function cuts() which take a single argument(string s). You need
not take any input or print anything. Return an int C if the cut is possible else return -1.
Expected Time Complexity: O(|s|*|s|*|s|).
Expected Auxiliary Space: O(|s|).
Constraints:
1<= |s| <=50
solution -:
• C++ solution
class Solution{
public:
return dp[l];
}
};
• Java solution
class Solution{
for(int i=1;i<=l;i++)
{
int index=i-1;
if(c[index]=='0')
{
dp[i]=-1;
}
else
{
dp[i]=-1;
int t=1000;
long count=0;
for(int j=0;j<i;j++)
{
if(c[index-j]=='1')
{
count+=num(j);
if(check(count)&dp[index-j]!=-1)
{
int w=1+dp[index-j];
t=(w<t)?w:t;
}
}
}
if(t!=1000){
dp[i]=t;
}
}
}
return dp[l];
Input: ABC
Output: [ABC, ACB, BAC, BCA, CAB, CBA]
Explanation:Given string ABC has permutations in 6 forms as ABC, ACB,
BAC, BCA, CAB and CBA .
Input: ABSG
Output: [ABGS, ABSG, AGBS, AGSB, ASBG, ASGB, BAGS, BASG, BGAS,
BGSA, BSAG, BSGA, GABS, GASB, GBAS, GBSA, GSAB, GSBA, SABG,
SAGB, SBAG, SBGA, SGAB, SGBA]
Explanation: Given string ABSG has 24 permutations.
solution -:
• C++ solution
class Solution {
public:
vector<string> find_permutation(string S) {
vector<string> res;
sort([Link](), [Link]());
do {
res.push_back(S);
} while (next_permutation([Link](), [Link]()));
return res;
}
};
• Java solution
class Solution {
HashSet<String> H;
Validate an IP Address
Difficulty: medium
[Link] are given a string s in the form of an IPv4 Address. Your task is to validate
an IPv4 Address, if it is valid return true otherwise return false.
IPv4 addresses are canonically represented in dot-decimal notation, which
consists of four decimal numbers, each ranging from 0 to 255, separated
by dots, e.g., [Link]
A valid IPv4 Address is of the form x1.x2.x3.x4 where 0 <= (x1, x2, x3, x4)
<= 255. Thus, we can write the generalized form of an IPv4 address as (0-
255).(0-255).(0-255).(0-255)
Note: Here we are considering numbers only from 0 to 255 and any additional leading
zeroes will be considered invalid.
Examples:
Input : s = [Link]
Output : true
Explanation: Here, the IPv4 address is as per the criteria mentioned and also all
four decimal numbers lies in the mentioned range.
Input : s = 5555..555
Output : false
Constraints:
1<=[Link]() <=15
solution -:
• C++ solution
class Solution {
public:
int isValid(string s) {
int n = [Link]();
if (n < 7)
return 0;
vector<string> v;
stringstream ss(s);
while ([Link]()) {
string substr;
getline(ss, substr, '.');
v.push_back(substr);
}
if ([Link]() != 4)
return 0;
class Solution {
if (n < 7)
return false;
if (count != 4)
return false;
return true;
}
}
Largest number in K swaps
Difficulty: medium
[Link] a number K and string str of digits denoting a positive integer, build the
largest number possible by performing swap operations on the digits of str at
most K times.
Examples:
Input : K = 4 str = "1234567"
Output : 7654321
Explanation: Three swaps can make the input 1234567 to 7654321, swapping
1with 7, 2 with 6 and finally 3 with 5
Output : 5543333
Explanation: Three swaps can make the input 3435335 to 5543333, swapping 3 with 5, 4 with
5 and finally 3 with 4
Your task:
You don't have to read input or print anything. Your task is to complete the
function findMaximumNum() which takes the string and an integer as input and returns a
string containing the largest number formed by perfoming the swap operation at most k times.
Constraints:
1 ≤ |str| ≤ 30
1 ≤ K ≤ 10
solution -:
• C++ solution
class Solution
{
public:
void match(string& str, string& res)
{
for(int i = 0; i < [Link](); i++)
{
if( res[i] > str[i] )
return;
if( res[i] < str[i] )
{
res = str;
return;
}
}
}
public:
void setDigit(string& str, int index, string& res, int k)
{
if(k == 0 || index == [Link]() - 1)
{
match(str, res);
return;
}
int maxDigit = 0;
public:
string findMaximumNum(string str, int k)
{
string res = str;
setDigit(str, 0, res, k);
return res;
}
};
• Java solution
class Res {
static String max = "";
}
class Solution
{
public static void findMaximumNumUtil(char ar[], int k, Res r)
{
if (k == 0) return;
int n = [Link];
for (int i = 0; i < n - 1; i++)
{
for (int j = i + 1; j < n; j++)
{
if (ar[j] > ar[i])
{
char temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
if ([Link](st) < 0)
{
[Link] = st;
}
findMaximumNumUtil(ar, k - 1, r);
temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
}
}
}
}
Difficulty: medium
[Link] automobile company manufactures both a two wheeler (TW) and a four
wheeler (FW). A company manager wants to make the production of both types of
vehicle according to the given data below:
•1st data, Total number of vehicle (two-wheeler + four-wheeler)=v
•2nd data, Total number of wheels = W
Input :
200 -> Value of V
540 -> Value of W
Output :
TW =130 FW=70
Explanation:
130+70 = 200 vehicles
(70*4)+(130*2)= 540 wheels
Constraints :
•2<=W
•W%2=0
•V<W
solution -:
• C++ solution
#include <bits/stdc++.h>
using namespace std;
int main () {
int v, w;
cin >> v >> w;
float x = ((4 * v) - w) / 2;
if ((w & 1) || w < 2 || w <= v) {
cout << "INVALID INPUT";
return 0;
}
cout << "TW=" << x << " " << "FW=" << v - x;
return 0;
}
• Java solution
import [Link];
int v = [Link]();
int w = [Link]();
[Link]();
}
}