0% found this document useful (0 votes)
12 views

Two Pointer

Uploaded by

IG Khan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Two Pointer

Uploaded by

IG Khan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

class Solution {

public void moveZeroes(int[] nums) {


int o = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i]!=0){
int temp = nums[o];
nums[o] = nums[i];
nums[i] = temp;
o++;
}
}
}
}
class Solution {
public boolean isSubsequence(String s, String t) {
int i,j;
for(i = 0,j = 0; i < s.length() && j<t.length();){
char sc = s.charAt(i);
char tc = t.charAt(j);
if(sc==tc){
i++;
j++;
}
else{
j++;
}
}
if(i==s.length()) return true;
return false;
}
}
class Solution {
public int maxArea(int[] height) {
int area = Integer.MIN_VALUE;
int l = 0, r = height.length-1;
while(l<r){
int smaller = Math.min(height[r],height[l]);
area = Math.max(Math.abs(r-l)*smaller,area);
if(height[l]<height[r]) l++;
else r--;
}
return area;
}
}
Using Sorting +Two Pointers→TC=O(nlogn),SC = O(1)

class Solution {
public int maxOperations(int[] nums, int k) {
Arrays.sort(nums);
int n = nums.length,l = 0,r = n-1;
while(l<r){
if(nums[l]+nums[r]==k){
maxOperations++;
l++;
r--;
}
else if(k<nums[l]+nums[r]) r--;
else l++;
}
return maxOperations;
}
}
Using HashMap→TC=O(n),SC=O(n)

class Solution {
public int maxOperations(int[] nums, int k) {
HashMap<Integer, Integer> numCount = new HashMap<>();
int maxOperations = 0;

for (int num : nums) {


int complement = k - num;
if (numCount.containsKey(complement) && numCount.get(complement) > 0)
{
maxOperations++;
numCount.put(complement, numCount.get(complement) - 1);
} else {
numCount.put(num, numCount.getOrDefault(num, 0) + 1);
}
}

return maxOperations;
}
}

You might also like