80% found this document useful (5 votes)
6K views8 pages

Juspay Coding Challenge Solutions

The document discusses three problems and their solutions in C++ and Java. The first problem involves sorting a string based on character frequency. The second problem involves removing stars and adjacent characters from a string. The third problem finds the longest consecutive sequence of numbers in a sorted list.

Uploaded by

Deepu Singh
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
80% found this document useful (5 votes)
6K views8 pages

Juspay Coding Challenge Solutions

The document discusses three problems and their solutions in C++ and Java. The first problem involves sorting a string based on character frequency. The second problem involves removing stars and adjacent characters from a string. The third problem finds the longest consecutive sequence of numbers in a sorted list.

Uploaded by

Deepu Singh
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
  • Problem 1: String Frequency Game
  • Problem 2: Car Race Stars
  • Problem 3: Longest Consecutive Subsequence

Q1 :Problem Statement :

Shivina wants to design a game for kids for their enjoyment as well as their knowledge . She
takes the string from the children and sorts the string by the property such that the character
which has the highest frequency will come first and the character which has the least frequency
will come last. Now you have to write a code for that and help shivina for getting the sorted
string according to the frequency which will have to be higher to lower.
Write an algorithmic code for this.
Constraint

1 <= [Link] <= 5 * 10^5


s consists of uppercase and lowercase English letters and digits

Input : s = "cccaaa"

Output : "cccaaa"

Explanation :
a and c have same frequency 3 , but a come before c in alphabet.

Input1 : s = "ccaaa"

Output1 : "aaacc"

Solution in C++:

#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int main() {
string s;
cin>>s;
unordered_map<char,int> m;

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

vector<pair<int,char>> vect;
for(auto v : m){
vect.push_back({ [Link],[Link]});
}

sort([Link](),[Link](),greater<pair<int,char>>());

string str;
for(auto v: vect){
string temp([Link],[Link]);
str=str+ temp;
}
cout<<str;
return 0;
}

Solution in Java:

import [Link].*;

public class Main {

public static String solution(String str) {


Map<Character, Integer> Map = new HashMap<>();
for (int i = 0; i < [Link](); i++) {
char ch = [Link](i);
if (![Link](ch)) {
[Link](ch, 1);
} else {
[Link](ch, [Link](ch) + 1);
}
}
List<Character> chars = new ArrayList<>([Link]());
[Link](chars, new Comparator<Character>() {
public int compare(Character ch1, Character ch2) {
return [Link](ch2) - [Link](ch1);
}
});
StringBuilder sb = new StringBuilder();
for (char ch : chars) {
int freq = [Link](ch);
for (int i = 0; i < freq; i++) {
[Link](ch);
}
}
return [Link]();
}

public static void main(String[] args) {


Scanner scan=new Scanner([Link]);
String str = [Link]();
String sortStr = solution(str);
[Link](sortStr);
}
}

Q2 : Problem Statement :

Ram, who have scares to stars, found himself constantly bothered by his friend's liking for them.
One day, his friend presented him with a game designed to help overcome his fear. In this
game, Ram is presented with a string containing a mix of characters and stars. His objective is
to select a star and eliminate both the star itself and the nearest non-star character to its left.
This process continues until there are no stars left in the string. Once all stars are removed,
Ram must return the remaining string. Can you help Ram by writing an algorithmic code ?

Constraints :
● 1<= [Link] <=105
● S consists of lowercase english letters and star *

Input 0 :
"leet**cod*e"

Output 0 :
"Lecoe"

Input 1 :
"erase*****"

Output 1 :
""

Input 2 :
"leet**cod*"
Output 2 :
"Leco"

Input 4 :
"erase***"

Output 4 :
“er”

Solution in C++:

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

int main() {
string s;
cin>>s;
string ans;

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

if([Link]() and ([Link]()!= '*' and s[i]== '*')){


ans.pop_back();
}
else ans.push_back(s[i]);
}

for(int i=0;i<[Link]();i++){
cout<<ans[i];
}
return 0;
}

Solution in Java:
import [Link].*;

public class Main {


public static String solution(String str){

Stack<Character> stack=new Stack<>();


for(int i=0;i<[Link]();i++){
char ch=[Link](i);
if(ch=='*')
[Link]();
else
[Link](ch);
}

return [Link]();
}
public static void main(String[] args) {
Scanner scan=new Scanner([Link]);
String str=[Link]();
[Link](solution(str));
[Link]();
}
}

Q3 : Problem Statement :

The school principal gathered students from different classes. They had to say their roll
numbers and line up in order from smallest to largest. They were to count consecutive
subsequences in this line. The main goal was to identify the longest consecutive sequence of 'n'
initial roll numbers. This activity was to make school fun and help students practice math and
organization
Your task is to write an algorithmic code to find the longest consecutive sequence.
Definition of consecutive sequence: Numbers that follow each other continuously in the order
from smallest to largest are called consecutive numbers.

Constraints :

0 <= [Link] <= 10^5

-10^9 <= nums[i] <= 10^9

Inputs :
6 = number of elements
[100,4,200,1,3,2] = elements

Output :

Explanation :
In ascending order : 1,2,3,4,100,200
Maximum consecutive sequence : 1,2,3,4 = 4

Solution in C++:

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

int main() {
int n;
cin>>n;
vector<int>nums;

for(int i=0;i<n;i++){
int t;
cin>>t;
nums.push_back(t);
}
vector<int> ans;
int counter = 1;
int maxi = INT_MIN;

if([Link]() == 0)
return 0;
else if([Link]() == 1){
cout<<1;
return 0;
}

sort([Link](),[Link]());
ans.push_back(nums[0]);
for(int i = 1;i < [Link]();i++){
if([Link]() + 1 == nums[i]){
ans.push_back(nums[i]);
counter++;
}else if([Link]()+1 != nums[i] && [Link]() != nums[i]){
[Link]();
ans.push_back(nums[i]);
maxi = max(maxi,counter);
counter = 1;
}
maxi = max(maxi, counter);
}

cout<<maxi;

return 0;
}

Solution in Java:

import [Link].*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n = [Link]();
ArrayList<Integer> nums = new ArrayList<>();
for (int i = 0; i < n; i++) {
int t = [Link]();
[Link](t);
}

ArrayList<Integer> ans = new ArrayList<>();


int counter = 1;
int maxi = Integer.MIN_VALUE;

if ([Link]() == 0) {
[Link](0);
return;
} else if ([Link]() == 1) {
[Link](1);
return;
}

[Link](nums);
[Link]([Link](0));
for (int i = 1; i < [Link](); i++) {
if ([Link]([Link]() - 1) + 1 == [Link](i)) {
[Link]([Link](i));
counter++;
} else if ([Link]([Link]() - 1) + 1 != [Link](i) && [Link]([Link]() - 1) !=
[Link](i)) {
[Link]();
[Link]([Link](i));
maxi = [Link](maxi, counter);
counter = 1;
}
maxi = [Link](maxi, counter);
}

[Link](maxi);
}
}

Common questions

Powered by AI

Sorting serves as a foundational step that simplifies subsequent operations in complex problems, as seen in character frequency arrangement and longest number sequence detection. It aligns inputs in a defined order, facilitating pattern recognition or ordered traversal. The disciplined structure provides predictable certainty, turning potentially ambiguous data into a uniformly accessible format. This is especially critical in frequency analysis or sequence detection where inherent ordering eases multi-partite operations like frequency sorting or consecutive sequence linking .

The use of a map for frequency counting offers constant average-time complexity for insertions and lookups, making it efficient for identifying character frequencies quickly. This structure suits dynamic frequency updates and is scalable with string size. However, potential limitations include overhead from hashing operations and larger memory footprint if the number of unique characters is high, which though unlikely, can incur additional costs compared to simpler arrays when constraints allow fixed character sets .

The algorithm first sorts the array of numbers to arrange them in ascending order. It then iterates through the sorted list, keeping track of consecutive numbers by using a counter. If the difference between successive numbers is exactly one, it continues to count. If a gap is found, the current sequence length is compared against the maximum found so far, updating the maximum if necessary. This ensures that it can find the longest run of consecutive integers .

The algorithm processes the string by iterating through each character. If a star (*) is encountered, the algorithm checks if there's a non-star character to its left (by analyzing the current state of the constructed 'ans' string). If so, it removes that character. By using a simple stack logic (pop for removal), it efficiently eliminates stars and their left-adjacent characters .

The design principle exemplified is the 'Last-In, First-Out' (LIFO) handling through a stack approach. By using a stack to control sequence and removal, the algorithm ensures only immediate, contextually-valid removals occur — i.e., a character right before a star is eliminated. This principle allows the algorithm to efficiently emulate sequential and dependent operations within string manipulation tasks, facilitating clear, linear processing steps .

The efficiency of the algorithm is determined by the use of a map to count frequencies, taking O(n) time, with n being the length of the string. Sorting the character-frequency pairs involves O(m log m) complexity, where m is the number of unique characters. Since m is considerably smaller than n in practical scenarios, this approach is efficient for the given constraint (up to 500,000 characters). Overall, the algorithm leverages efficient data structuring to offer good performance .

The algorithm emphasizes sequence detection by prioritizing sorting and single-pass sequence validation as opposed to direct operations on individual numbers. This shift acknowledges that sequence length is more crucial than individual numeric characteristics when determining the longest consecutive run. This design strategy reflects a holistic view of data relationships rather than isolated data points, seeking emergent patterns that manifest only in ordered contexts .

Shivina's algorithm utilizes a map to count the frequency of each character in the input string. It then stores these character-frequency pairs in a vector and sorts them in descending order of frequency. This ensures that characters with the highest frequency appear first in the output. The sorting step in the process is key to arranging characters by their frequency in descending order .

The approach balances complexity by using sorting, which is O(n log n), followed by a single pass to determine sequence length, O(n). This trade-off optimizes the balance between the simplicity of the implementation and handling up to 100,000 numbers efficiently. It recognizes the practical feasibility of sorting as a preemptive step compared to directly seeking sequences, which might involve more intricate bookkeeping or additional structures, reflecting a strategic compromise for realistic constraints .

An optimization might involve using a bidirectional string processing technique, such as two-pointer traversal, which bypasses unnecessary stack operations by directly filtering and reconstructing the string in a single pass. This approach could minimize both time and space complexity by removing stars and non-star pairs without entire stack management, thus accelerating the problem resolution, especially in strings with high concentrations of stars .

Q1 :Problem Statement :
Shivina wants to design a game for kids for their enjoyment as well as their knowledge . She
takes th
for(auto v : m){
vect.push_back({ v.second,v.first});
}
sort(vect.begin(),vect.end(),greater<pair<int,char>>());
string str;
sb.append(ch);
}
}
return sb.toString();
}
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
Stri
Output 2 :
"Leco"
Input 4 :
"erase***"
Output 4 :
“er”
Solution in C++:
#include <iostream>
#include<bits/stdc++.h>
using nam
public static String solution(String str){
Stack<Character> stack=new Stack<>();
for(int i=0;i<str.length();i++){
char ch=str
[100,4,200,1,3,2] = elements
Output :
4
Explanation :
In ascending order : 1,2,3,4,100,200
Maximum consecutive sequence : 1,2
}else if(ans.back()+1 != nums[i] && ans.back() != nums[i]){
ans.clear();
ans.push_back(nums[i]);
maxi = max(maxi,counter);
co
for (int i = 1; i < nums.size(); i++) {
if (ans.get(ans.size() - 1) + 1 == nums.get(i)) {
ans.add(nums.get(i));
counter++;
}

You might also like