Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions src/main/java/com/ibm/code_pair/bookish_spoon/LRUCache.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.ibm.code_pair.bookish_spoon;

public class LRUCache {

/**
* Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.
*
* Implement the LRUCache class:
*
* LRUCache(int capacity) Initializes the LRU cache with positive size capacity.
* int get(int key) Return the value of the key if the key exists, otherwise return -1.
* void put(int key, int value) Update the value of the key if the key exists.
*
* Otherwise, add the key-value pair to the cache.
* If the number of keys exceeds the capacity from this operation, evict the least recently used key.
*
* The functions get and put must each run in O(1) average time complexity.
* @param args
*/

public static void main(String[] args) {

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package com.ibm.code_pair.bookish_spoon;

/**
* <h1>Trapping Rain Water</h1>
*
* <p>
* Given <code>n</code> non-negative integers representing an elevation map where
* the width of each bar is 1, compute how much water it can trap after raining.
* </p>

*
* <h2>Input Example</h2>
*
* <pre>
* height = [0,1,0,2,1,0,1,3,2,1,2,1]
* </pre>
*
* <h2>Output</h2>
*
* <pre>
* 6
* </pre>
*
* <h2>Constraints</h2>
* <ul>
* <li>1 ≤ height.length ≤ 20,000</li>
* <li>0 ≤ height[i] ≤ 100,000</li>
* </ul>
*
*/
public class TrappingRainWater {

public static void main(String[] args) {
int[] height = {0,1,0,2,1,0,1,3,2,1,2,1};

TrappingRainWater solver = new TrappingRainWater();
int result = solver.trap(height);

System.out.println("Trapped water = " + result);
}

/**
* Two-pointer implementation of the Trapping Rain Water problem.
*
* @param height array representing elevation bars
* @return total water trapped
*/
private int trap(int[] height) {
private static int trap(int[] arr) {

int n = arr.length;
if(n<=2) return 0;
int[] prefix = new int[n];
int[] postfix = new int[n];

//prefix traversal
prefix[0] = arr[0];
for(int i = 1; i<n; i++) {
prefix[i] = Math.max(prefix[i-1], arr[i]);
}


postfix[n-1] = arr[n-1];
for(int i = n-2; i>=0; i--) {
postfix[i] = Math.max(postfix[i+1], arr[i]);
}

int result = 0;
for(int i=1; i<n-1; i++) {
result += Math.min(prefix[i], postfix[i]) - arr[i];
}
return result;
}
}
}

Binary file added src/main/resources/trapping-rain-water.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.