Here we have given some important two pointer problems below:
1. Valid Palindrome:
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string
Given a string
s
, return true
if it is a palindrome, or false
otherwise.-> Solution:
class Solution {
public:
bool isPalindrome(string s) {
int low=0;
int high=s.length()-1;
while(low<high){
while(!iswalnum(s[low]) && low<high){
low++;
}
while(!iswalnum(s[high]) && low<high){
high--;
}
if(tolower(s[low])!=tolower(s[high])){
return false;
}
low++;
high--;
}
return true;
}
};
Time complexity: O(n)
Problem link: Valid Palindrome - LeetCode
2. Two Sum II:
Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order,find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where
1 <= index1 < index2 <= numbers.length
.-> Solution:
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int>vec;
int st=0;
int en=numbers.size()-1;
while(st<en){
int sum = numbers[st]+numbers[en];
if(sum<target){
st++;
}
else if(sum>target){
en--;
}
else{
vec.push_back(st+1);
vec.push_back(en+1);
break;
}
}
return vec;
}
};
Time complexity: O(n)
Problem Link: Two Sum II - Input Array Is Sorted - LeetCode
3. 3SUM:
Given an integer array nums, return all the triplets
[nums[i], nums[j],
nums[k]]
such that i != j
, i != k
, and j != k
, and nums[i] + nums[j] + nums[k] == 0
.class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(),nums.end());
vector<vector<int>>vec;
for(int i=0;i<nums.size();i++){
int ans = nums[i];
if(i>0 && nums[i-1]==ans) continue;
else{
int st=i+1,en=nums.size()-1;
while(st<en){
if(ans+nums[st]+nums[en]>0) en--;
else if (ans+nums[st]+nums[en]<0) st++;
else{
vec.push_back({ans,nums[st],nums[en]});
while(st<en && nums[st]==nums[st+1]){
st++;
}
st++;
while(st<en && nums[en]==nums[en-1]){
en--;
}
en--;
}
}
}
}
return vec;
}
};
Time complexity: O(n^2)
Problem link: 3Sum - LeetCode
Comments
Post a Comment