DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Winning Camp Worksheet (Java)
Day: 19
Name : Saurav Singha UID : 21BCS5421
Subject : Java Section : SC-904 (B)
Date : 19/06/2024
Problem 1: Rotate String
Solution:
class Solution {
public boolean rotateString(String s, String goal) {
return s.length() == goal.length() && (s + s).contains(goal);
}
}
Output:
Problem 2: Maximum number of words found in a string
Solution:
class Solution {
public int mostWordsFound(String[] sentences) {
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
int max = 0;
for (String sentence : sentences) {
max = Math.max(max, sentence.split(" ").length);
}
return max;
}
}
Output:
Problem 3: Maximum frequency Stack
Solution:
import java.util.HashMap;
import java.util.Map;
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
import java.util.Stack;
class FreqStack {
private final Map<Integer, Stack<Integer>> stacks;
private final Map<Integer, Integer> frequencies;
private int maxFrequency;
public FreqStack() {
this.stacks = new HashMap<>();
this.frequencies = new HashMap<>();
this.maxFrequency = 0;
}
public void push(int val) {
int frequency = frequencies.getOrDefault(val, 0) + 1;
this.maxFrequency = Math.max(frequency, this.maxFrequency);
frequencies.put(val, frequency);
stacks.putIfAbsent(frequency, new Stack<>());
stacks.get(frequency).add(val);
}
public int pop() {
Stack<Integer> stack = stacks.get(this.maxFrequency);
int val = stack.pop();
if (stack.isEmpty()) {
stacks.remove(this.maxFrequency--);
}
frequencies.put(val, frequencies.get(val) - 1);
return val;
}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
}
Output:
Problem 4: Combination Sum II
Solution:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> ds = new ArrayList<>();
Arrays.sort(candidates);
combination(candidates, target, ans, ds, 0);
return ans;
}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
private void combination(int[] candidates, int target, List<List<Integer>> ans,
List<Integer> ds, int index) {
if (target == 0) {
ans.add(new ArrayList<>(ds));
return;
}
for (int i = index; i < candidates.length; i++) {
if (i > index && candidates[i] == candidates[i - 1]) continue;
if (candidates[i] > target) break;
ds.add(candidates[i]);
combination(candidates, target - candidates[i], ans, ds, i + 1);
ds.remove(ds.size() - 1);
}
}
}
Output: