Skip to content

Commit

Permalink
commit
Browse files Browse the repository at this point in the history
  • Loading branch information
abhishekghoshh committed Jan 12, 2025
1 parent 9202219 commit 2508703
Show file tree
Hide file tree
Showing 15 changed files with 630 additions and 93 deletions.
6 changes: 3 additions & 3 deletions README-old.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
- [Kadane’s Algorithm : Maximum Subarray Sum in an Array for consecutive elements](/src/com/problems/array/MaxSumForConsecutiveElements.java)
- [Print maximum Subarray Sum in an Array for consecutive elements](/src/com/problems/array/PrintMaxSumForConsecutiveElements.java)
- [Maximum Subarray Sum in an Array for non-consecutive elements](/src/com/problems/array/MaxSumForNonConsecutiveElements.java)
- [Rearrange Array Elements by Sign](/src/com/problems/array/RearrangeArrayElementsBySign.java)

- [next_permutation : find next lexicographically greater permutation](/src/com/problems/array/NextPermutation.java)
- [Leaders in an Array](/src/com/problems/array/LeadersInAnArray.java)
- [Set Matrix Zero](/src/com/problems/array/SetMatrixToZero.java)
Expand All @@ -49,9 +49,9 @@

-
- [Maximum Product Subarray in an Array](/src/com/problems/array/MaximumProductSubarrayInAnArray.java)
- [Car Fleet](/src/com/problems/array/CarFleet.java) **TBD**
-
- [3Sum Closest](/src/com/problems/array/ThreeSumClosest.java)
- [Trapping Rainwater](/src/com/problems/array/TrappingRainWater.java)


- [Find the Count of Monotonic Pairs I](/src/com/problems/array/FindTheCountOfMonotonicPairs.java)
- [Adjacent Increasing Subarrays Detection I](/src/com/problems/array/AdjacentIncreasingSubarraysDetection1.java)
Expand Down
8 changes: 7 additions & 1 deletion resources/arrays.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@
- [Count inversions in an array](/src/com/problems/array/CountInversionInArray.java)
- [Count Reverse Pairs](/src/com/problems/array/ReversePairs.java)

- [Car Fleet](/src/com/problems/array/CarFleet.java)

### Swap sort
- [Swap sort](/src/com/algo/sort/SwapSort.java)
- [Find the repeating and missing numbers](/src/com/problems/array/RepeatAndMissingNumber.java)
Expand Down Expand Up @@ -125,4 +127,8 @@
- [Remove Duplicates from Sorted Array](/src/com/problems/array/RemoveDuplicateFromSortedArray.java)
- [Remove Duplicates from Sorted Array II](/src/com/problems/array/RemoveDuplicateFromSortedArray2.java)
- [Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold](/src/com/problems/array/NumberOfSubArraysOfSizeKAndAverageGreaterThanOrEqualToThreshold.java)
- [Boats to Save People](/src/com/problems/array/BoatsToSavePeople.java)
- [Boats to Save People](/src/com/problems/array/BoatsToSavePeople.java)
- [Rearrange Array Elements by Sign](/src/com/problems/array/RearrangeArrayElementsBySign.java)
- [Bag of Tokens](/src/com/problems/array/BagOfTokens.java)
- [Minimum Length of String After Deleting Similar Ends](/src/com/problems/array/MinimumLengthOfStringAfterDeletingSimilarEnds.java)
- [Trapping Rainwater](/src/com/problems/array/TrappingRainWater.java)
1 change: 1 addition & 0 deletions resources/dynamic-programming.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,4 +108,5 @@
- [Sum of Good Subsequences](/src/com/problems/dp/SumOfGoodSubsequences.java)
- [Count Paths With the Given XOR Value](/src/com/problems/dp/CountPathsWithTheGivenXORValue.java)
- [Champagne Tower](/src/com/problems/dp/ChampagneTower.java)
- [Maximum Amount of Money Robot Can Earn](/src/com/problems/dp/MaximumAmountOfMoneyRobotCanEarn.java)

1 change: 1 addition & 0 deletions resources/graph.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
- [Bellman Ford](/src/com/problems/graph/BellmanFord.java)
- [Floyd Warshall](/src/com/problems/graph/FloydWarshall.java)
- [Find the City With the Smallest Number of Neighbors at a Threshold Distance](/src/com/problems/graph/FindTheCityWithTheSmallestNumberOfNeighbors.java)
- [Minimize the Maximum Edge Weight of Graph](/src/com/problems/graph/MinimizeTheMaximumEdgeWeightOfGraph.java)

### Minimum Spanning Tree
- [Minimum Spanning Tree - Theory](/src/com/problems/graph/MinimumSpanningTree.java)
Expand Down
1 change: 1 addition & 0 deletions resources/recursion.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
- [Reverse of an array](/src/com/problems/recursion/ReverseOfAnArray.java)
- [String is palindrome or not](/src/com/problems/recursion/StringIsPalindrome.java)
- [Height of a binary tree/Max depth of a Binary tree](/src/com/problems/binarytree/HeightOfBinaryTree.java)
- [Zigzag Grid Traversal With Skip](/src/com/problems/binarytree/ZigzagGridTraversalWithSkip.java)
- [Recursive Implementation of atoi()](/src/com/problems/string/StringToInteger.java)
- [Pow(x, n)](/src/com/problems/binarysearch/PowerOfXtoN.java)
- [Count Good Numbers](/src/com/problems/recursion/CountGoodNumbers.java)
Expand Down
1 change: 1 addition & 0 deletions resources/stack.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
- [Sum of subarray minimum](/src/com/problems/stack/SumOfSubarrayMinimum.java)
- [Sum of subarray maximum](/src/com/problems/stack/SumOfSubarrayMaximum.java)
- [Sum of Subarray Ranges](/src/com/problems/stack/SumOfSubarrayRanges.java)
- [Trapping Rainwater](/src/com/problems/array/TrappingRainWater.java)

- [Asteroid Collision](/src/com/problems/stack/AsteroidCollision.java)
- [Maximal Rectangles in a Binary Matrix](/src/com/problems/stack/MaxRectangularAreaOfBinaryMatrix.java)
Expand Down
71 changes: 71 additions & 0 deletions src/com/problems/array/BagOfTokens.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package com.problems.array;

import java.util.Arrays;

/*
*
* problem links:
* https://leetcode.com/problems/bag-of-tokens/
*
* Solution link:
* https://www.youtube.com/watch?v=prI82maTivg
*
* https://neetcode.io/solutions/bag-of-tokens
* */

public class BagOfTokens {

/*
*
* You start with an initial power of power, an initial score of 0, and a bag of tokens given as an integer array tokens,
* Your goal is to maximize the total score by strategically playing these tokens. In one move, you can play an 'unplayed'
* token in one of the two ways (but not both for the same token)
*
* Face-up: If your current power is at least tokens[i], you may and loose tokens[i] power and gaining 1 score.
* Face-down: If your current score is at least 1, you may play and gain tokens[i] power and losing 1 score.
*
* Return the maximum possible score you can achieve after playing any number of tokens.
* */
public static void main(String[] args) {
type1();
type2();
}

// todo classic example of 2 pointers
// we will be little greedy here
// first we will sort the array, if we need to score we will hit the lowest token
// and if we need the power we will try to hit the maximum token possible
// as score will either increase or decrease by 1 only
private static void type2() {
int[] tokens = {100, 200, 300, 400};
int power = 200;
int ans = bagOfTokensScore2(tokens, power);
System.out.println(ans);
}

public static int bagOfTokensScore2(int[] tokens, int power) {
Arrays.sort(tokens);
int n = tokens.length;
int i = 0, j = n - 1;
int max = 0, score = 0;
while (i <= j) {
// if we have the power we will try to score as much as possible
while (i <= j && power >= tokens[i]) {
score++;
power -= tokens[i++];
}
max = Math.max(max, score);
// if the score has to be at least 1 then we can not hit any token, if 0 then we will break from here
if (score == 0) break;
// if there is any token available on the right side then we will hit that and grab the power
if (i <= j) {
score--;
power += tokens[j--];
}
}
return max;
}

private static void type1() {
}
}
2 changes: 1 addition & 1 deletion src/com/problems/array/CarFleet.java
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ private static int carFleet2(int[] position, int target, int[] speed) {
return fleet;
}

// this is a greedy approach
// todo this is a greedy approach
// whatever the speed is, the first car will always go at first,
// so we will create an array of (n*2) of (pos,time to reach target)
// and sort the cars as per the position, closest car will come first
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package com.problems.array;
/*
*
* problem links:
* https://leetcode.com/problems/minimum-length-of-string-after-deleting-similar-ends/description/
*
* Solution link:
* https://www.youtube.com/watch?v=318hrWVr_5U
*
* https://neetcode.io/solutions/minimum-length-of-string-after-deleting-similar-ends
* */

// Tags: Array, String, Two pointer
public class MinimumLengthOfStringAfterDeletingSimilarEnds {
public static void main(String[] args) {
type1();
type2();
}

// todo optimized approach
// classic problem of 2 pointer
// if the in both end the character are same then we will shrink
// we will shrink till the characters are same
private static void type2() {
String s = "aabccabba";
int ans = minimumLength2(s);
System.out.println(ans);
}


public static int minimumLength2(String s) {
char[] arr = s.toCharArray();
int n = arr.length;
int i = 0, j = n - 1;
while (i < j) {
// if characters are different then we will break
if (arr[i] != arr[j]) break;
char ch = arr[i];
// shrinking the left side
while (i < j && arr[i] == ch) i++;
// if (i to j) all characters are same then after left shrinking i wil go till j he answer will be 0 that time
if (i == j) return 0;
// shrinking the right side
while (i < j && arr[j] == ch) j--;
}
// length of the string
return (j - i + 1);
}

private static void type1() {
}
}
41 changes: 31 additions & 10 deletions src/com/problems/array/RearrangeArrayElementsBySign.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@
*
* problem links:
* https://leetcode.com/problems/rearrange-array-elements-by-sign/description/
* https://www.codingninjas.com/studio/problems/alternate-numbers_6783445
* https://www.naukri.com/code360/problems/alternate-numbers_6783445
*
* Solution link:
* https://www.youtube.com/watch?v=h4aBagy4Uok
* https://www.youtube.com/watch?v=SoPmcGzz9-E
*
* https://takeuforward.org/arrays/rearrange-array-elements-by-sign/
* https://neetcode.io/solutions/rearrange-array-elements-by-sign
* */
public class RearrangeArrayElementsBySign {
public static void main(String[] args) {
Expand All @@ -23,7 +25,16 @@ public static void main(String[] args) {
// space complexity O(n)
private static void type2() {
int[] nums = {3, 1, -2, -5, 2, -4};
int[] result = new int[nums.length];
int[] result = rearrangeArray2(nums);
PrintUtl.print(result);
}

private static int[] rearrangeArray2(int[] nums) {
int n = nums.length;
int[] result = new int[n];
// we will use 2 pointer one for positive and one for negative
// positive will start from 0 and negative will start from 1
// if we find positive then increment pIndex by 2 and for negative we will increment nIndex by 2
int pIndex = 0;
int nIndex = 1;
for (int num : nums) {
Expand All @@ -35,24 +46,34 @@ private static void type2() {
nIndex += 2;
}
}
PrintUtl.print(result);
return result;
}

// time complexity O(2n)
// space complexity O(n)
private static void type1() {
int[] nums = {3, 1, -2, -5, 2, -4};
int[] ans = rearrangeArray1(nums);
PrintUtl.print(nums);
}

private static int[] rearrangeArray1(int[] nums) {
int n = nums.length;
int[] setP = new int[n / 2];
int[] setN = new int[n / 2];
int n2 = n / 2;
// using 2 different array for
int[] setP = new int[n2];
int[] setN = new int[n2];
int i1 = 0, i2 = 0;
for (int i = 0; i < n; i++)
if (nums[i] > 0) setP[i1++] = nums[i];
else setN[i2++] = nums[i];
for (int i = 0; i < n / 2; i++) {
for (int num : nums) {
if (num > 0)
setP[i1++] = num;
else
setN[i2++] = num;
}
for (int i = 0; i < n2; i++) {
nums[2 * i] = setP[i];
nums[2 * i + 1] = setN[i];
}
PrintUtl.print(nums);
return nums;
}
}
Loading

0 comments on commit 2508703

Please sign in to comment.