0% found this document useful (0 votes)
4 views24 pages

String Medium Coding

Uploaded by

soyixeb661
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views24 pages

String Medium Coding

Uploaded by

soyixeb661
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Question with Solution

Rearrange String with Hashes

Difficulty:medium

Ask By Company -: capgemini

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.

char* moveHash(char str[],int n);

example :-

Sample Test Case

Input:

Move#Hash#to#Front

Output:

###MoveHashtoFront

solution -:

• C++ solution
#include <iostream>
#include <cstring>
using namespace std;

char* moveHash(char str[], int n) {


char str1[100], str2[100];
int j = 0, k = 0;

for (int i = 0; str[i]; i++) {


if (str[i] == '#')
str1[j++] = str[i]; // Collect '#' characters
else
str2[k++] = str[i]; // Collect non-'#' characters
}

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

int len = strlen(a); // Calculate the length of the input


moveHash(a, len); // Call the function to move '#'
return 0;
}
• Java solution

import [Link];

public class MoveHash {


public static String moveHash(String str) {
StringBuilder hashPart = new StringBuilder();
StringBuilder nonHashPart = new StringBuilder();

for (int i = 0; i < [Link](); i++) {


if ([Link](i) == '#')
[Link]('#'); // Collect '#' characters
else
[Link]([Link](i)); // Collect non-'#' characters
}

return [Link]() + [Link]();


}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
String input = [Link](); // Input string

[Link](moveHash(input));

[Link]();
}
}

Factorials of large numbers


Difficulty:medium

Ask By Company -: Morgan Stanley , Microsoft , Samsung , MakeMyTrip ,MAQ


software , Adobe , philips ,BrowserStack

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.

Expected Time Complexity : O(N2)


Expected Auxilliary Space : O(1)
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;
}
}
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 {

public ArrayList<Integer> factorial(int N) {


ArrayList<Integer> number = new ArrayList<>();
[Link](1);

for (int i = 2; i <= N; i++) {


multiply(i, number);
}

[Link](number);
return number;
}

private void multiply(int n, ArrayList<Integer> number) {


int carry = 0;

for (int i = 0; i < [Link](); i++) {


int num = n * [Link](i);
[Link](i, (num + carry) % 10);
carry = (num + carry) / 10;
}

while (carry > 0) {


[Link](carry % 10);
carry /= 10;
}
}
}

First unique character in a string

Difficulty:medium

Ask By Company -: Ola , Walmart , Amdocs

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” .

Detailed explanation ( Input/output format, Notes, Images )


Input format :
The first line of input contains a single integer T, denoting the number of test cases.

The first line of each test case contains a positive integer N, which represents the length of the
string.

The next line of each test case contains a string S.


Output Format :
For each test case, return the index of the first unique character, and if there is no unique
character return “-1”.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given
function.
Constraint :
1 <= T <= 100
1 <= N <= 10^4

Time Limit: 1 sec

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

int firstUniqueCharacter(string s , int n) {

for (int i=0 ; i<n ; i++) {

for (int j=0 ; j<n ; j++) {


if(i!=j) {
if(s[i] == s[j]){
unique = false;
break;
}

if(unique == true) {
return i+1;
}

}
return -1.
return -1;
}

• Java solution

public class Solution {


public static int firstUniqueCharacter(String s, int n) {

for (int i = 0; i < n; i++) {

boolean unique = true;


so we will return it.
for (int j = 0; j < n; j++) {
if (i != j) {
if ([Link](i) == [Link](j)) {
unique = false;
break;
}

if (unique == true) {
return i + 1;
}

return -1;
}

Reverse each word in a given string


Difficulty:medium

Ask By Company -: Paytm , zoho , amazon

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.

Expected Time Complexity:O(|S|).


Expected Auxiliary Space:O(|S|).

Constraints:
1<=|S|<=10^5

solution -:
• C++ solution

#include<bits/stdc++.h>
using namespace std;

void printWords(string str)


{
string word;

stringstream iss(str);

while (iss >> word){


reverse([Link](),[Link]());
cout<<word<<" ";
}
}

int main()
{
string s = "GeeksforGeeks is good to learn";
printWords(s);
return 0;
}
• Java solution

import [Link];
import [Link];

public class reverseIndividual {

public static void main(String[] args) {

String str = "Welcome to GFG";

String result = [Link]([Link](" "))


.stream()
.map(s -> new StringBuilder(s).reverse())
.collect([Link](" "));

[Link](result);

String to Integer
Difficulty:medium

Ask By Company -:

Q5. Implement the myAtoi(string s) function, which converts a string to a 32-bit


signed integer.
The algorithm for myAtoi(string s) is as follows:

1. Whitespace: Ignore any leading whitespace ( " " ).


2. Signedness: Determine the sign by checking if the next character is '-' or '+' , assuming positivity is
neither present.
3. Conversion: Read the integer by skipping leading zeros until a non-digit character is encountered or the
end of the string is reached. If no digits were read, then the result is 0.
4. Rounding: If the integer is out of the 32-bit signed integer range [-2 31 , 2 31 - 1] , then round the
integer to remain in the range. Specifically, integers less than -2 31 should be rounded to -2 31, and
integers greater than 2 31 - 1 should be rounded to 2 31 - 1 .

Return the integer as the final result.


Examples

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)

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)

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:

Reading stops at the first non-digit character 'w'.

Constraints:

• 0 <= [Link] <= 200


• s consists of English letters (lower-case and upper-case), digits ( 0-9 ), ' ' , '+' , '-' , and '.' .

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;

while(index < len && s[index] == ' '){


++index;
}

bool isNegative = false;

if(index < len){

if(s[index] == '-'){
isNegative = true;
++index;
} else if (s[index] == '+'){
++index;
}

int result = 0;

while(index < len && isDigit(s[index])){

int digit = s[index] - '0';

if(result > (INT_MAX / 10) || (result == (INT_MAX / 10) && digit > 7)){
return isNegative ? INT_MIN : INT_MAX;
}

result = (result * 10) + digit; // adding digits at their desired place-


value

++index;
}

return isNegative ? -result : result;


}

private:
bool isDigit(char ch){
return ch >= '0' && ch <= '9';
}
};

Factorials of large numbers

Difficulty:medium

Ask By Company -: Microsoft , sumsung , Adobe

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]

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.

Expected Time Complexity : O(N2)


Expected Auxilliary Space : O(1)

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;
}
}

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 {

public ArrayList<Integer> factorial(int N) {


ArrayList<Integer> number = new ArrayList<>();
[Link](1);

for (int i = 2; i <= N; i++) {


multiply(i, number);
}

[Link](number);
return number;
}

private void multiply(int n, ArrayList<Integer> number) {


int carry = 0;

for (int i = 0; i < [Link](); i++) {


int num = n * [Link](i);
[Link](i, (num + carry) % 10);
carry = (num + carry) / 10;
}

while (carry > 0) {


[Link](carry % 10);
carry /= 10;
}
}
}

Minimum Swaps for Bracket Balancing


Difficulty:medium

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

public 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 ([Link](i) == '[') {
countLeft++;
if (imbalance > 0) {
swap += imbalance;
imbalance--;
}
} else if ([Link](i) == ']') {
countRight++;
imbalance = countRight - countLeft;
}
}

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 .

A shift on s consists of moving the leftmost character of s to the rightmost position.

• For example, if s = "abcde" , then it will be "bcdea" after one shift.


Example:-

Input: s = "abcde", goal = "cdeab"


Output: true

Input: s = "abcde", goal = "abced"


Output: false

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);
}
}

Cutting Binary String

Difficulty:medium

Ask By Company -: Microsoft , google , walmart , filpkart

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:

long long int num(int y)


{
if(y==0){return 1;}
long long int x=2;
for(int i=1;i<y;i++)
{
x=x<<1;
}
return x;
}
bool check(long long int n)
{
if(n==0){return false;}
if(n==1){return true;}
if(n%5!=0){return false;}
else{return check(n/5);}
}
int cuts(string s)
{
int l=[Link]();
int dp[l+1];
dp[0]=0;
for(int i=1;i<=l;i++)
{
int index=i-1;
if(s[index]=='0'){dp[i]=-1;}
else
{
dp[i]=-1;
int t=1000;
long long int count=0;
for(int j=0;j<i;j++)
{
if(s[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];
}
};

• Java solution

class Solution{

static int cuts(String s)


{
char c[]=[Link]();
int l=[Link];
int dp[]=new int[l+1];
dp[0]=0;

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];

static long num(int y)


{
if(y==0)return 1;
long x=2;
for(int i=1;i<y;i++)
{
x=x<<1;
}
return x;
}

static boolean check(long n)


{
if(n==0){return false;}
if(n==1){return true;}
if(n%5!=0){return false;}
else{return check(n/5);}
}
}

Permutations of a given string


Difficulty:medium

Ask By Company -: Amazon , microsoft , cisco , walmart


Q10. Given a string s. The task is to return a vector of string
of all unique permutations of the given string, s that may contain dulplicates in
lexicographically sorted order.
Examples:

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.

Expected Time Complexity: O(n! * n)


Expected Space Complexity: O(n! * n)
Constraints:
1 <= [Link] <= 5

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;

public List<String> find_permutation(String S) {


int n = [Link]();
char c[] = [Link]();
H = new HashSet<>();
[Link](S);
fun(0, c);
List<String> A = new ArrayList<>();
for (String i : H) {
[Link](i);
}
[Link](A);
return A;
}

public void fun(int i, char c[]) {


if (i == [Link])
return;
for (int j = i; j < [Link]; j++) {
if (c[i] != c[j]) {
char temp = c[i];
c[i] = c[j];
c[j] = temp;
String st = "";
for (char ch : c) {
st += ch;
}
[Link](st);
fun(i + 1, c);
temp = c[i];
c[i] = c[j];
c[j] = temp;
} else {
fun(i + 1, c);
}
}
}
}

Validate an IP Address
Difficulty: medium

Ask By Company -: zoho , amazon , microsoft , qualcomm

[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

Explanation: 5555..555 is not a valid. IPv4 address, as the middle two


portions are missing.

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;

for (int i = 0; i < [Link](); i++) {


string temp = v[i];
if ([Link]() > 1) {
if (temp[0] == '0')
return 0;
}

for (int j = 0; j < [Link](); j++) {


if (isalpha(temp[j]))
return 0;
}

if (stoi(temp) > 255)


return 0;
}
return 1;
}
};
• Java solution

class Solution {

public boolean isValid(String s) {


int n = [Link]();

if (n < 7)
return false;

StringTokenizer st = new StringTokenizer(s, ".");


int count = 0;
while ([Link]()) {
String substr = [Link]();
count++;

if ([Link]() > 1 && [Link](0) == '0')


return false;

for (int j = 0; j < [Link](); j++) {


if (![Link]([Link](j)))
return false;
}

if ([Link](substr) > 255)


return false;
}

if (count != 4)
return false;

return true;
}
}
Largest number in K swaps
Difficulty: medium

Ask By Company -: zoho , amazon , microsoft , qualcomm , makmytrip , walmart

[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

Input : K = 3 str = "3435335

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.

Expected Time Complexity: O(n!/(n-k)!) , where n = length of input string


Expected Auxiliary Space: O(n)

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;

for(int i = index; i < [Link](); i++)


maxDigit = max(maxDigit, str[i] - '0');

if( str[index] - '0' == maxDigit )


{
setDigit(str, index + 1, res, k);
return;
}

for(int i = index + 1; i < [Link](); i++)


{
if( str[i] - '0' == maxDigit )
{
swap(str[index], str[i]);
setDigit(str, index + 1, res, k - 1);
swap(str[index], str[i]);
}
}
}

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;

String st = new String(ar);

if ([Link](st) < 0)
{
[Link] = st;
}
findMaximumNumUtil(ar, k - 1, r);

temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
}
}
}
}

public static String findMaximumNum(String str, int k)


{
Res r = new Res();
[Link] = str;
findMaximumNumUtil([Link](), k, r);
return [Link];
}
}

Character Balance Check

Difficulty: medium

Ask By Company -: TCS

[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

The task is to find how many two-wheelers as well as four-wheelers need to


manufacture as per the given data.
Example :

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];

public class Main {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

int v = [Link]();
int w = [Link]();

float x = ((4 * v) - w) / 2.0f;

if ((w % 2 != 0) || w < 2 || w <= v) {


[Link]("INVALID INPUT");
} else {
[Link]("TW=" + x + " FW=" + (v - x));
}

[Link]();
}
}

You might also like