It contains all the coderbyte examples
Java/AdditivePersistence.java at master · metin-aksu/Java
public
class CountFrequency
{
public static void main(String[]
args) {
Map<Character, Long>
map = "com.saravanjs.java24.console.Interviews"
.chars()
.mapToObj(c ->(char) c)
.collect(Collectors.groupingBy(c ->
c, Collectors.counting()));
System.out.println(map);
}
}
public class FindDuplicates {
public static void main(String[]
args) {
var list = List.of(4,7,3,7,3,7);
Set<Integer>
set = new HashSet<>();
list.stream()
.filter(n ->
!set.add(n))
.forEach(System.out::println);
}
}
7
3
7
public
class FirstNonRepeatedChar
{
public static void main(String[]
args) {
var list = List.of("","a","bb","cdd","eef","gghh","ijjj","kkkl");
list.stream().map(c ->
findFirstNonRepeated(c))
.forEach(System.out::println);
list.stream().map(c ->
findFirstNonRepeated2(c))
.forEach(System.out::println);
}
public static char findFirstNonRepeated(String
str) {
int n = str.length();
for (int
i = 0; i <
n; i++)
{
char ch = str.charAt(i);
if (str.indexOf(ch)
== str.lastIndexOf(ch))
{
return ch;
}
}
return '\0'; //
No non-repeated character found
}
public static char findFirstNonRepeated2(String
str) {
return (char) IntStream.range(0, str.length())
.filter(i ->
str.indexOf(str.charAt(i))
== str.lastIndexOf(str.charAt(i)))
.mapToObj(i ->
str.charAt(i))
.findFirst()
.orElse('\0');
}
}
public class MaxCounters {
public static void main(String[]
args) {
maxcounters(5, new
int[] {3, 4, 4, 6, 8, 1, 4, 4});
}
private static int[] maxcounters(int
N, int[]
A) {
int[] counters = new
int[N];
int maxCount = 0;
int minCount = 0;
for (int
value : A)
{
String msg = "";
int index = 0;
if (value
== N + 1)
{
msg += "
exceeded update minCount in all the boxes";
minCount = maxCount;
} else if (value
>= 1 && value
<= N) {
index = value
- 1;
if (counters[index]
< minCount) {
msg += "
update with minCount ";
counters[index]
= minCount;
}
counters[index]
+= 1;
if (maxCount
< counters[index])
{
msg += "
maxCount";
maxCount = counters[index];
}
} else {
msg += "
no action";
}
System.out.println("value
%d index %d minCount %d maxCount %d counters %s : %s "
.formatted(value, index,
minCount, maxCount, Arrays.toString(counters),
msg));
}
for (int
i = 0; i <
N; i++)
{
if (counters[i]
< minCount) {
counters[i]
= minCount;
}
System.out.println("
minCount %d counters[i] %d counters %s : "
.formatted(
minCount, counters[i],
Arrays.toString(counters)));
}
return counters;
}
}
value 3 index 2 minCount 0 maxCount 1 counters [0, 0, 1, 0, 0] : maxCount
value 4 index 3 minCount 0 maxCount 1 counters [0, 0, 1, 1, 0] :
value 4 index 3 minCount 0 maxCount 2 counters [0, 0, 1, 2, 0] : maxCount
value 6 index 0 minCount 2 maxCount 2 counters [0, 0, 1, 2, 0] : exceeded update minCount in all the boxes
value 8 index 0 minCount 2 maxCount 2 counters [0, 0, 1, 2, 0] : no action
value 1 index 0 minCount 2 maxCount 3 counters [3, 0, 1, 2, 0] : update with minCount maxCount
value 4 index 3 minCount 2 maxCount 3 counters [3, 0, 1, 3, 0] :
value 4 index 3 minCount 2 maxCount 4 counters [3, 0, 1, 4, 0] : maxCount
minCount 2 counters[i] 3 counters [3, 0, 1, 4, 0] :
minCount 2 counters[i] 2 counters [3, 2, 1, 4, 0] :
minCount 2 counters[i] 2 counters [3, 2, 2, 4, 0] :
minCount 2 counters[i] 4 counters [3, 2, 2, 4, 0] :
minCount 2 counters[i] 2 counters [3, 2, 2, 4, 2] :
public class MaxNonoverlappingSegments {
public static void main(String[]
args) {
int result = maxNonoverlappingSegments(new
int[] {1, 3, 7, 9, 9},
new int[] {5, 6, 8, 9, 10}
);
System.out.println(result);
}
private static int maxNonoverlappingSegments(int[]
A, int[]
B) {
int n = A.length;
if (n ==
0) return 0;
// Since segments are already sorted by end points (B
is non-decreasing)
// We can greedily select segments that don't overlap
int count = 1;
// Count of chosen segments
int lastEnd = B[0];
// End point of the last chosen segment
// Start from the second segment
for (int
i = 1; i <
n; i++)
{
// If current segment doesn't overlap with
last chosen segment
if (A[i]
> lastEnd) {
count++;
lastEnd = B[i];
}
}
return count;
}
}
3
public class MaxProductOfThree {
public static void main(String[]
args) {
int result = maxProductOfThree(new
int[] {1, 2, 5, 6}
);
System.out.println(result);
result = maxProductOfThree(new
int[] {-10, -8, 1, 2, 7}
);
System.out.println(result);
}
static int maxProductOfThree(int[]
A) {
/*
[1, 2, 5, 6]
→ 6
× 5 × 2
= 60
[-10, -8, 1, 2, 7]
7 × (-10) ×
(-8)
= 560
*/
Arrays.sort(A);
int n = A.length;
int candidate1 = A[n - 1]
* A[n - 2]
* A[n - 3];
int candidate2 = A[0]
* A[1]
* A[n - 1];
return Math.max(candidate1, candidate2);
}
}
60
560
public class MaxSliceSum {
public static void main(String[]
args) {
int result = maxSliceSum(new
int[] {-5, -7,
-2} );
System.out.println(result);
result = maxSliceSum(new
int[] {3, 2,
-6, 4, 0}
);
System.out.println(result);
result = maxSliceSum(new
int[] {-10, -8, 1, 2, 7}
);
System.out.println(result);
result = maxSliceSum(new
int[] {1, 3, 7,
-9, 9}
);
System.out.println(result);
result = maxSliceSum(new
int[] {5, 9,
-6, 8, 10}
);
System.out.println(result);
result = maxSliceSum(new
int[] {5, 9,
-17, 8, 10}
);
System.out.println(result);
}
static int maxSliceSum(int[]
A) {
int endingHere = A[0];
int maxSlice = A[0];
for (int
i = 1; i <
A.length; i++)
{
endingHere = Math.max(A[i],
endingHere + A[i]);
maxSlice = Math.max(maxSlice, endingHere);
}
return maxSlice;
}
}
-2
5
10
11
26
18
public class MinMaxSum {
public static void miniMaxSum(int[]
arr) {
long total = 0L;
long min = Long.MAX_VALUE;
long max = Long.MIN_VALUE;
for (int num
: arr) {
total += num;
if (num <
min) {
min = num;
} else if (num
> max) {
max = num;
}
}
long minSum = total
- max;
long maxSum = total
- min;
System.out.println(minSum
+ " " + maxSum);
}
public static void main(String[]
args) {
int[] arr =
{1, 2, 3, 4, 5};
miniMaxSum(arr);
}
}
10 14
public class TieRopes {
public static void main(String[]
args) {
int[] arr =
{1, 2, 3, 4, 1, 1, 3};
tieRopes(4, arr);
}
public static int tieRopes(int
K, int[]
A) {
int count = 0;
long current = 0;
for (int
rope : A)
{
current += rope;
if (current
>= K) {
count++;
current = 0;
}
String str = "current
%d rope %d count %d ".formatted(current, rope, count);
System.out.println(str);
}
return count;
}
}
current 1 rope 1 count 0
current 3 rope 2 count 0
current 0 rope 3 count 1
current 0 rope 4 count 2
current 1 rope 1 count 2
current 2 rope 1 count 2
current 0 rope 3 count 3
public
class CyclicRotation {
public static void main(String[]
args) {
int[] result = cyclicRotation(new
int[]{3, 8, 9, 7, 6},
3);
System.out.println("\nFinal
Result = " + Arrays.toString(result));
}
static int[] cyclicRotation(int[]
A, int K)
{
int n = A.length;
System.out.println("Input
Array : " + Arrays.toString(A));
System.out.println("K
: " + K);
System.out.println("N
: " + n);
// Empty array
if (n ==
0) {
System.out.println("Empty
array. Returning...");
return A;
}
// Avoid unnecessary full rotations
K %= n;
System.out.println("K
% N : " + K);
// No rotation needed
if (K ==
0) {
System.out.println("No
rotation needed.");
return A;
}
int[] result = new
int[n];
System.out.println("\nLoop
Execution:");
System.out.println("-------------------------------------------------------------");
System.out.println("i
| Formula | Source Index | Value | Result");
System.out.println("-------------------------------------------------------------");
for (int
i = 0; i <
n; i++)
{
int sourceIndex =
(i + n - K)
% n;
result[i]
= A[sourceIndex];
System.out.printf(
"%d | (%d + %d - %d) %% %d = %d | %13d
| %5d | %s%n",
i,
i,
n,
K,
n,
sourceIndex,
sourceIndex,
A[sourceIndex],
Arrays.toString(result)
);
}
return result;
}
}
Input Array : [3, 8, 9, 7, 6]
K : 3
N : 5
K % N : 3
Loop Execution:
-------------------------------------------------------------
i | Formula | Source Index | Value | Result
-------------------------------------------------------------
0 | (0 + 5 - 3) % 5 = 2 | 2 | 9 | [9, 0, 0, 0, 0]
1 | (1 + 5 - 3) % 5 = 3 | 3 | 7 | [9, 7, 0, 0, 0]
2 | (2 + 5 - 3) % 5 = 4 | 4 | 6 | [9, 7, 6, 0, 0]
3 | (3 + 5 - 3) % 5 = 0 | 0 | 3 | [9, 7, 6, 3, 0]
4 | (4 + 5 - 3) % 5 = 1 | 1 | 8 | [9, 7, 6, 3, 8]
Final Result = [9, 7, 6, 3, 8]
public class CommonPrimeDivisors {
private static int gcd(int
a, int b)
{
int x = a;
int y = b;
if (a ==
b) {
System.out.printf("---
GCD(%d, %d) => %d %n", a, b, a);
return a;
}
while (b !=
0) {
int temp = b;
b = a % b;
a = temp;
}
System.out.printf("---
GCD(%d, %d) => %d %n", x, y, a);
return a;
}
private static int reduceByCommonPrimeDivisors(int
value,
int
gcdValue,
String
name) {
System.out.printf("
Reducing %s=%d%n", name, value);
while (value
!= 1 && gcdValue
> 1) {
int g = gcd(value, gcdValue);
if (g ==
1) {
System.out.printf("
No more common factors for %s%n", name);
break;
}
value /= g;
System.out.printf("
%s reduced to: %d%n", name, value);
}
return value;
}
private static boolean hasSamePrimeDivisors(int
a, int b)
{
System.out.printf("Checking
pair: (%d, %d)%n", a, b);
if (a ==
0 || b ==
0) {
boolean result = a ==
b;
System.out.printf("
Zero case: %b%n", result);
return result;
}
int gcdValue = gcd(a, b);
int originalA = a;
int originalB = b;
a = reduceByCommonPrimeDivisors(a, gcdValue, "A");
b = reduceByCommonPrimeDivisors(b, gcdValue, "B");
boolean result = a ==
1 && b ==
1;
System.out.printf("
Final result for (%d, %d): %b (A reduced=%d, B reduced=%d)%n",
originalA, originalB, result, a, b);
return result;
}
public static int commonPrimeDivisors(int[]
A, int[]
B) {
int Z = A.length;
int count = 0;
System.out.printf("===
Starting CommonPrimeDivisors ===%n");
System.out.printf("Number
of pairs: %d%n", Z);
for (int
i = 0; i <
Z; i++)
{
System.out.printf("%n---
Pair %d ---%n", i);
if (hasSamePrimeDivisors(A[i],
B[i]))
{
count++;
System.out.printf("✓ Count increased to: %d%n", count);
} else {
System.out.printf("✗ Not same prime divisors%n");
}
}
System.out.printf("%n===
Final count: %d ===%n", count);
return count;
}
public static void main(String[]
args) {
int[] A =
{15,10,3};
int[] B =
{75,30,5};
int result = commonPrimeDivisors(A, B);
System.out.println("\nFinal
Result = " + result);
}
}
=== Starting CommonPrimeDivisors ===
Number of pairs: 3
--- Pair 0 ---
Checking pair: (15, 75)
--- GCD(15, 75) => 15
Reducing A=15
--- GCD(15, 15) => 15
A reduced to: 1
Reducing B=75
--- GCD(75, 15) => 15
B reduced to: 5
--- GCD(5, 15) => 5
B reduced to: 1
Final result for (15, 75): true (A reduced=1, B reduced=1)
✓ Count increased to: 1
--- Pair 1 ---
Checking pair: (10, 30)
--- GCD(10, 30) => 10
Reducing A=10
--- GCD(10, 10) => 10
A reduced to: 1
Reducing B=30
--- GCD(30, 10) => 10
B reduced to: 3
--- GCD(3, 10) => 1
No more common factors for B
Final result for (10, 30): false (A reduced=1, B reduced=3)
✗ Not same prime divisors
--- Pair 2 ---
Checking pair: (3, 5)
--- GCD(3, 5) => 1
Reducing A=3
Reducing B=5
Final result for (3, 5): false (A reduced=3, B reduced=5)
✗ Not same prime divisors
=== Final count: 1 ===
Final
Result = 1
@Data
public class LeaderboardEntry implements
Comparable<LeaderboardEntry>,
Cloneable {
private final String name;
private final int score;
private int rank;
public LeaderboardEntry(String
name, int score)
{
this.name
= name;
this.score
= score;
}
@Override
public LeaderboardEntry clone()
{
try {
return (LeaderboardEntry) super.clone();
} catch (CloneNotSupportedException
e) {
throw new RuntimeException(e);
}
}
@Override
public int compareTo(LeaderboardEntry
other) {
// Higher scores first
return Integer.compare(other.score, this.score);
}
@Override
public String toString()
{
return String.format(
"Rank=%d Name=%s Score=%d",
rank,
name,
score
);
}
}
@Data
class Leaderboard {
private final List<LeaderboardEntry>
entries = new ArrayList<>();
public void add(String
name, int score)
{
entries.add(new
LeaderboardEntry(name, score));
Collections.sort(entries);
calculateRanks();
}
public void calculateRanks()
{
if (entries.isEmpty())
{
return;
}
int rank = 1;
entries.get(0).setRank(rank);
for (int
i = 1; i <
entries.size();
i++) {
LeaderboardEntry previous = entries.get(i - 1);
LeaderboardEntry current = entries.get(i);
if (current.getScore()
!= previous.getScore())
{
rank++;
}
current.setRank(rank);
}
}
public int getRankByName(String
name) {
return entries.stream().filter(x ->
x.getName().equals(name))
.map(x ->
x.getRank())
.findFirst().orElse(-1);
}
public void print() {
entries.forEach(System.out::println);
}
public Leaderboard clone()
{
Leaderboard cloned = new
Leaderboard();
List<LeaderboardEntry>
clonedEntries =
new ArrayList<>(
entries.stream()
.map(LeaderboardEntry::clone)
.toList());
cloned.getEntries().addAll(clonedEntries);
return cloned;
}
}
class Main {
public static void main(String[]
args) {
Leaderboard board = new
Leaderboard();
board.add("Tom", 100);
board.add("Bob", 100);
board.add("Mary", 50);
board.add("John", 40);
board.add("Steve", 40);
board.add("David", 20);
board.add("Kevin", 10);
System.out.println("Initial
Leaderboard:");
board.print();
int[] aliceScores =
{5, 25, 50, 120};
for (int
score : aliceScores)
{
Leaderboard cloned = board.clone();
cloned.add("Alice", score);
System.out.printf(
"Alice score=%d Rank=%d%n",
score,
cloned.getRankByName("Alice"));
System.out.println("\nFinal
Leaderboard:");
cloned.print();
}
}
}
Initial Leaderboard:
Rank=1 Name=Tom Score=100
Rank=1 Name=Bob Score=100
Rank=2 Name=Mary Score=50
Rank=3 Name=John Score=40
Rank=3 Name=Steve Score=40
Rank=4 Name=David Score=20
Rank=5 Name=Kevin Score=10
Alice score=5 Rank=6
Final Leaderboard:
Rank=1 Name=Tom Score=100
Rank=1 Name=Bob Score=100
Rank=2 Name=Mary Score=50
Rank=3 Name=John Score=40
Rank=3 Name=Steve Score=40
Rank=4 Name=David Score=20
Rank=5 Name=Kevin Score=10
Rank=6 Name=Alice Score=5
Alice score=25 Rank=4
Final Leaderboard:
Rank=1 Name=Tom Score=100
Rank=1 Name=Bob Score=100
Rank=2 Name=Mary Score=50
Rank=3 Name=John Score=40
Rank=3 Name=Steve Score=40
Rank=4 Name=Alice Score=25
Rank=5 Name=David Score=20
Rank=6 Name=Kevin Score=10
Alice score=50 Rank=2
Final Leaderboard:
Rank=1 Name=Tom Score=100
Rank=1 Name=Bob Score=100
Rank=2 Name=Mary Score=50
Rank=2 Name=Alice Score=50
Rank=3 Name=John Score=40
Rank=3 Name=Steve Score=40
Rank=4 Name=David Score=20
Rank=5 Name=Kevin Score=10
Alice score=120 Rank=1
Final Leaderboard:
Rank=1 Name=Alice Score=120
Rank=2 Name=Tom Score=100
Rank=2 Name=Bob Score=100
Rank=3 Name=Mary Score=50
Rank=4 Name=John Score=40
Rank=4 Name=Steve Score=40
Rank=5 Name=David Score=20
Rank=6 Name=Kevin Score=10
public class BinaryGap {
public static void main(String[]
args) {
System.out.println(binaryGap(1041));
System.out.println(binaryGap(529));
System.out.println(binaryGap(22));
}
static int binaryGap(int
N) {
// Convert to binary string
String binary = Integer.toBinaryString(N);
System.out.println("N="
+ N + ",
binary=" + binary);
int maxGap = 0;
int currentGap = 0;
boolean counting = false;
// Traverse the binary string
for (int
i = 0; i <
binary.length();
i++) {
if (binary.charAt(i)
== '1') {
if (counting)
{
// End of a gap, update max if needed
maxGap = Math.max(maxGap, currentGap);
System.out.println("
Gap found: " + currentGap + ",
maxGap=" + maxGap);
currentGap = 0;
} else {
// Start counting after first '1'
counting = true;
}
} else if (counting)
{
// We're inside a gap, increment counter
currentGap++;
}
}
System.out.println("Result:
" + maxGap);
return maxGap;
}
}
N=1041, binary=10000010001
Gap found: 5, maxGap=5
Gap found: 3, maxGap=5
Result: 5
5
N=529, binary=1000010001
Gap found: 4, maxGap=4
Gap found: 3, maxGap=4
Result: 4
4
N=22, binary=10110
Gap found: 1, maxGap=1
Gap found: 0, maxGap=1
Result: 1
1
public class TapeEquil {
public static void main(String[]
args) {
System.out.println(tapeEquil(new
int[] {3, 1, 2, 4, 3}));
}
static int tapeEquil(int[]
A) {
int n = A.length;
// Calculate total sum of all elements
int totalSum = 0;
for (int
num : A)
{
totalSum += num;
}
int leftSum = 0;
int minDiff = Integer.MAX_VALUE;
System.out.println("Total
sum: " + totalSum);
// Try each split position (between index 0-1, 1-2,
..., n-2-n-1)
for (int
p = 0; p <
n - 1; p++)
{
leftSum += A[p];
int rightSum = totalSum
- leftSum;
int diff = Math.abs(leftSum
- rightSum);
System.out.println("P="
+ p + ",
leftSum=" + leftSum + ",
rightSum=" + rightSum + ",
diff=" + diff);
if (diff
< minDiff) {
minDiff = diff;
}
}
System.out.println("Minimum
difference: " + minDiff);
return minDiff;
}
}
Total sum: 13
P=0, leftSum=3, rightSum=10, diff=7
P=1, leftSum=4, rightSum=9, diff=5
P=2, leftSum=6, rightSum=7, diff=1
P=3, leftSum=10, rightSum=3, diff=7
Minimum difference: 1
1
public class DiagonalDifference {
public static void main(String[]
args) {
List<List<Integer>>
arr = Arrays.asList(
Arrays.asList(1, 2, 3),
Arrays.asList(4, 5, 6),
Arrays.asList(9, 8, 9)
);
System.out.println(diagonalDifference(arr));
}
public static int diagonalDifference(List<List<Integer>>
arr) {
int n = arr.size();
int primarySum = 0;
int secondarySum = 0;
for (int
i = 0; i <
n; i++)
{
System.out.printf(
"Primary: matrix[%d][%d] = %d%n",
i,
i,
arr.get(i).get(i));
System.out.printf(
"Secondary: matrix[%d][%d] =
%d%n",
i,
n - 1 - i,
arr.get(i).get(n - 1 - i));
primarySum += arr.get(i).get(i);
secondarySum += arr.get(i).get(n - 1 - i);
}
return Math.abs(primarySum
- secondarySum);
}
}
Primary: matrix[0][0] = 1
Secondary: matrix[0][2] = 3
Primary: matrix[1][1] = 5
Secondary: matrix[1][1] = 5
Primary: matrix[2][2] = 9
Secondary: matrix[2][0] = 9
2
Two Sum
Given an array and a target, return indices of two numbers that add up to target.
Example:
nums =
[2,7,11,15]
target = 9
Output:
[0,1]
public
class TwoSum {
public static void main(String[]
args) {
// Test the solution
int[] nums
= {2, 7, 11, 15};
int target = 9;
int[] result = twoSum(nums, target);
System.out.println("Output:
[" + result[0]
+ "," + result[1]
+ "]");
result = twoSumBruteForce(nums, target);
System.out.println("Output:
[" + result[0]
+ "," + result[1]
+ "]");
result = twoSumPair(nums, target);
System.out.println("Output:
[" + result[0]
+ "," + result[1]
+ "]");
result = twoSumHashMap(nums, target);
System.out.println("Output:
[" + result[0]
+ "," + result[1]
+ "]");
result = twoSumIntPair(nums, target);
System.out.println("Output:
[" + result[0]
+ "," + result[1]
+ "]");
result = twoSumStream(nums, target);
System.out.println("Output:
[" + result[0]
+ "," + result[1]
+ "]");
result = twoSumIndexTrack(nums, target);
System.out.println("Output:
[" + result[0]
+ "," + result[1]
+ "]");
}
public static int[] twoSum(int[]
nums, int target)
{
// Create a map to store number -> index
Map<Integer, Integer>
map = new HashMap<>();
// Iterate through the array
for (int
i = 0; i <
nums.length; i++)
{
int complement = target
- nums[i];
// If complement exists in map, we found
our pair
if (map.containsKey(complement))
{
return new int[]{map.get(complement),
i};
}
// Store current number with its index
map.put(nums[i],
i);
}
// Return empty array if no solution found (problem
guarantees one solution)
return new int[]{};
}
public static int[] twoSumBruteForce(int[]
nums, int target)
{
for (int
i = 0; i <
nums.length; i++)
{
for (int
j = i + 1; j <
nums.length; j++)
{
if (nums[i]
+ nums[j]
== target) {
return new int[]{i, j};
}
}
}
return new int[]{};
}
static class Pair {
int index;
int value;
Pair(int index, int
value) {
this.index
= index;
this.value
= value;
}
}
public static int[] twoSumPair(int[]
nums, int target)
{
return IntStream.range(0, nums.length)
.mapToObj(i ->
new Pair(i, nums[i]))
.flatMap(pair1
-> IntStream.range(pair1.index
+ 1, nums.length)
.mapToObj(i ->
new Pair(i, nums[i]))
.filter(pair2
-> pair1.value
+ pair2.value
== target)
.map(pair2
-> new int[]{pair1.index, pair2.index}))
.findFirst()
.orElse(new
int[]{});
}
public static int[] twoSumHashMap(int[]
nums, int target)
{
Map<Integer, Integer>
map = new HashMap<>();
AtomicInteger index = new
AtomicInteger(0);
return Arrays.stream(nums)
.mapToObj(num
-> {
int currentIndex = index.getAndIncrement();
int complement = target
- num;
if (map.containsKey(complement))
{
return new int[]{map.get(complement),
currentIndex};
}
map.put(num, currentIndex);
return null;
})
.filter(result
-> result != null)
.findFirst()
.orElse(new
int[]{});
}
record IntPair(int
first, int second)
{}
public static int[] twoSumIntPair(int[]
nums, int target)
{
return IntStream.range(0, nums.length)
.boxed()
.flatMap(i ->
IntStream.range(i + 1, nums.length)
.filter(j ->
nums[i]
+ nums[j]
== target)
.mapToObj(j ->
new int[]{i, j}))
.findFirst()
.orElse(new
int[]{});
}
public static int[] twoSumStream(int[]
nums, int target)
{
Map<Integer, Integer>
map = new HashMap<>();
return IntStream.range(0, nums.length)
.filter(i ->
{
int complement = target
- nums[i];
if (map.containsKey(complement))
{
return true;
}
map.put(nums[i],
i);
return false;
})
.mapToObj(i ->
new int[]{map.get(target
- nums[i]),
i})
.findFirst()
.orElse(new
int[]{});
}
record IndexedValue(int
index, int value)
{}
public static int[] twoSumIndexTrack(int[]
nums, int target)
{
List<IndexedValue>
indexed = IntStream.range(0, nums.length)
.mapToObj(i ->
new IndexedValue(i, nums[i]))
.collect(Collectors.toList());
return indexed.stream()
.flatMap(iv1
-> indexed.stream()
.filter(iv2
-> iv2.index
> iv1.index)
.filter(iv2
-> iv1.value
+ iv2.value
== target)
.map(iv2
-> new int[]{iv1.index, iv2.index}))
.findFirst()
.orElse(new
int[]{});
}
}
public class ValidParentheses {
public static boolean isValid(String
s) {
Stack<Character>
stack = new Stack<>();
for (char
c : s.toCharArray())
{
if (c ==
'(') {
stack.push(')');
System.out.println(stack);
} else if (c ==
'{') {
stack.push('}');
System.out.println(stack);
} else if (c ==
'[') {
stack.push(']');
System.out.println(stack);
} else if (stack.pop()
== c) {
System.out.println(stack);
} else {
System.out.println(stack
+ " found " + c + "
is different ");
return false;
}
}
return stack.isEmpty();
}
public static boolean isValid2(String
s) {
Stack<Character>
stack = new Stack<>();
for (char
c : s.toCharArray())
{
// Push opening brackets onto the stack
if (c ==
'(' || c ==
'{' || c ==
'[') {
stack.push(c);
}
// Handle closing brackets
else {
// If stack is empty, no matching opening
bracket
if (stack.isEmpty())
{
return false;
}
char top = stack.pop();
// Check if the closing bracket matches the
top of stack
if (c ==
')' && top !=
'(') {
return false;
}
if (c ==
'}' && top !=
'{') {
return false;
}
if (c ==
']' && top !=
'[') {
return false;
}
}
}
// Stack should be empty if all brackets are matched
return stack.isEmpty();
}
public static void main(String[]
args) {
System.out.println(isValid2("({[]})"));
// true
System.out.println(isValid2("(]"));
// false
System.out.println(isValid2("()"));
// true
System.out.println(isValid2("([)]"));
// false
System.out.println(isValid2("{"));
// false }
}
}
public
class LongestSubstring
{
public
static void main(String[] args) {
System.out.println(lengthOfLongestSubstring4("bbtablud")); // 3
}
public
static int lengthOfLongestSubstring(String s) {
Set<Character> set = new HashSet<>();
int left = 0;
int maxLength = 0;
System.out.println(s);
for (int right = 0; right < s.length(); right++) {
char current = s.charAt(right);
// If character exists, shrink window from left
while (set.contains(current)) {
set.remove(current);
left++;
System.out.println(left + " : " + right + " : " + maxLength + " : " + set + " found "
+ current);
}
// Add current character and update max
set.add(current);
maxLength = Math.max(maxLength, right - left + 1);
System.out.println(left + " : " + right + " : " + maxLength + " : " + set );
}
return maxLength;
}
public
static int lengthOfLongestSubstring2(String s) {
List<Character> window = new ArrayList<>();
int maxLength = 0;
System.out.println(s);
for (char c : s.toCharArray()) {
// If character exists, remove everything before and including
it
if (window.contains(c)) {
int index = window.indexOf(c);
// Remove all elements up to and including the duplicate
window.subList(0, index + 1).clear();
}
// Add current character
window.add(c);
// Update max length
maxLength = Math.max(maxLength, window.size());
System.out.println(" window " + window + " maxLength " + maxLength + " " + c );
}
return maxLength;
}
public
static int lengthOfLongestSubstring4(String s) {
if (s == null || s.isEmpty()) return 0;
int maxLength = 0;
int left = 0;
System.out.println("Processing: \"" + s + "\"");
System.out.println("----------------------------------------");
for (int right = 0; right < s.length(); right++) {
char current = s.charAt(right);
// Get current window substring
String window = s.substring(left, right);
// Find duplicate in the window
int duplicateIndex = window.indexOf(current);
// If found, move left to skip the duplicate
if (duplicateIndex != -1) {
left = left + duplicateIndex + 1;
}
// Update max length
int currentLength = right - left + 1;
maxLength = Math.max(maxLength, currentLength);
// Visualize current window
System.out.println("Window: \"" + s.substring(left, right + 1) +
"\" (indices " + left + "-" + right +
"), Length: " + currentLength + ", Max: "
+ maxLength);
}
return maxLength;
}
}
Processing: "bbtablud"
----------------------------------------
Window: "b" (indices 0-0), Length: 1, Max: 1
Window: "b" (indices 1-1), Length: 1, Max: 1
Window: "bt" (indices 1-2), Length: 2, Max: 2
Window: "bta" (indices 1-3), Length: 3, Max: 3
Window: "tab" (indices 2-4), Length: 3, Max: 3
Window: "tabl" (indices 2-5), Length: 4, Max: 4
Window: "tablu" (indices 2-6), Length: 5, Max: 5
Window: "tablud" (indices 2-7), Length: 6, Max: 6
6
public class PassingCars {
public
static int solution(int[] A) {
int eastCars = 0;
int passingPairs = 0;
for (int i = 0; i < A.length; i++) {
if (A[i] == 0) {
eastCars++;
} else {
passingPairs += eastCars;
}
}
return passingPairs;
}
public
static void main(String[] args) {
int[][] testCases = {
{0, 1, 0, 1, 1},
{0, 1},
{1, 0},
{0, 0, 0, 0},
{1, 1, 1, 1},
{0, 1, 1},
{0, 0, 1, 1},
{1, 0, 1, 0, 1},
{0, 0, 0, 1, 1, 1},
{1, 1, 0, 0, 1, 1}
};
for (int i = 0; i < testCases.length; i++) {
int[] arr = testCases[i];
System.out.println("Test " + (i+1) + ": " +
java.util.Arrays.toString(arr) +
" → " + solution(arr));
}
}
}
Array: [0, 1, 0, 1, 1]
Index: 0 1 2 3 4
East: → →
West: ← ← ←
Passing pairs:
(0,1) → east at 0 passes west at 1
(0,3) → east at 0 passes west at 3
(0,4) → east at 0 passes west at 4
(2,3) → east at 2 passes west at 3
(2,4) → east at 2 passes west at 4
Total:
5 passing cars
Test 1: [0, 1, 0, 1, 1] → 5
Test 2: [0, 1] → 1
Test 3: [1, 0] → 0
Test 4: [0, 0, 0, 0] → 0
Test 5: [1, 1, 1, 1] → 0
Test 6: [0, 1, 1] → 2
Test 7: [0, 0, 1, 1] → 4
Test 8: [1, 0, 1, 0, 1] → 3
Test 9: [0, 0, 0, 1, 1, 1] → 9
Test 10: [1, 1, 0, 0, 1, 1] → 4