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
35 changes: 35 additions & 0 deletions Problem1.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@

//Time Complexity: O(n)
// Space Complexity: O(1)

//we use two pointers to find the left wall and right wall along with the current left and right index
//if we have a bigger right wall, we just worry about the left wall
//if we have a bigger left wall, we just worry about the right wall
//we can trap water if the current wall is smaller than the left/right wall
//we update the left/right wall if we find a bigger one
//we move the left pointer when we have a bigger right wall, otherwise we move the right pointer

class Solution {
public int trap(int[] height) {
int n=height.length,res=0;
int l=0,lw=0;
int r=n-1,rw=n-1;

while(l<r){
if(height[r]>height[l]){ // we do have a bigger right wall, just worry about the left wall
if(height[lw]>height[l]){
res+=height[lw]-height[l];
}else
lw=l;
l++;
}else{ // we do have a bigger left wall, just worry about the right wall
if(height[rw]>height[r])
res+=height[rw]-height[r];
else
rw=r;
r--;
}
}
return res;
}
}
30 changes: 30 additions & 0 deletions Problem2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@

// Time Complexity: O(n)
// Space Complexity: O(n)


// Create a bucket array of size n+1 to count how many papers have each citation count.
// If a paper has >= n citations, put it in bucket[n] (since h-index cannot exceed n).
// Traverse buckets from high to low, keeping a running total of papers.
// The first index i where the running total >= i is the h-index. If no such i exists, return 0.

class Solution {
public int hIndex(int[] citations) {
int n=citations.length;
int bucket[]=new int[n+1];

for(int i=0;i<n;i++){
if(citations[i]>=n)
bucket[n]++;
else
bucket[citations[i]]++;
}
int sum=0;
for(int i=n;i>=0;i--){
sum+=bucket[i];
if(sum>=i)
return i;
}
return 0;
}
}
26 changes: 26 additions & 0 deletions Problem3.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@

// Time Complexity: O(n)
// Space Complexity: O(1)

// We use the reverse method to reverse the elements in the array
// We first reverse the first n-k elements, then we reverse the last k elements
// Finally, we reverse the whole array to get the desired result

class Solution {
public void rotate(int[] nums, int k) {
int n=nums.length;
k=k%n;
reverse(nums,0,n-k-1);
reverse(nums,n-k,n-1);
reverse(nums,0,n-1);
}
void reverse(int a[],int l,int r){
while(l<r){
int t=a[l];
a[l]=a[r];
a[r]=t;
l++;
r--;
}
}
}