LeetCode Blind 75 - Part 1
06 Jun 2021In this blog I’ll be posting the codes (C++) and hints for the Array related questions. You can find the link to the curated Blind-75 link here.
1. Two Sum
Problem Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Hint: Iterating through the array
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> ans;
for(int i=0; i<nums.size(); i++){
for(int j=i+1;j<nums.size(); j++){
if(nums[i]+nums[j]==target){
ans.push_back(i);
ans.push_back(j);
}
}
}
return ans;
}
};
2. Best Time to Buy and Sell Stock
Problem You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
Hint : Finding the minimum and maximum such that profit is maximized
class Solution {
public:
int maxProfit(vector<int>& prices) {
int mi = INT_MAX;
int profit = 0;
int n=prices.size();
for(int i=0; i<n; i++){
mi = min(mi,prices[i]);
profit = max(profit,(prices[i]-mi));
}
return profit;
}
};
3. Contains Duplicate
Problem Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.
Hint : Using hashmap for optimization
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_map<int,bool> c;
for(int i=0; i<nums.size(); i++){
pair<int,bool> p(nums[i],true);
if(c.find(nums[i])!=c.end())
return true;
else
c.insert(p);
}
return false;
}
};
4. Product of Array Except Self
Problem Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. You must write an algorithm that runs in O(n) time and without using the division operation.
Hint : using dynamic programming, we move in both directions from the beginning and the end
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
vector<int> dp(nums.size(),1);
int left = 1, right = 1;
for(int i=0, j=nums.size()-1; i<nums.size(),j>=0; i++,--j){
dp[i]*=left;
dp[j]*=right;
left*=nums[i];
right*=nums[j];
}
return dp;
}
};
5. Maximum Subarray
Problem Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Hint : Cadanes algorithm, watch this video for reference
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int meh = 0, msf = INT_MIN;
for(int i=0; i<nums.size(); i++){
meh = meh + nums[i];
if(meh < nums[i])
meh = nums[i];
if(msf < meh)
msf = meh;
}
return msf;
}
};
6. Maximum Product Subarray
Problem Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product. It is guaranteed that the answer will fit in a 32-bit integer. A subarray is a contiguous subsequence of the array.
Hint : Here if we want to find the max product we need to calculate both maximum and minimum at each step because when minimum gets multiplied by another negative number it might become maximum.
class Solution {
public:
int maxProduct(vector<int>& nums) {
int n = nums.size();
int cmax = nums[0];
int pmin = nums[0];
int pmax = nums[0];
int product = nums[0];
int cmin;
for(int i=1; i<n; i++){
cmax = max(pmin * nums[i],max(pmax * nums[i], nums[i]));
cmin = min(pmin * nums[i],min(pmax * nums[i], nums[i]));
product = max(cmax,product);
pmax = cmax;
pmin = cmin;
}
return product;
}
};
7. Find Minimum in rotated sorted array
Problem Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become:
[4,5,6,7,0,1,2] if it was rotated 4 times.
[0,1,2,4,5,6,7] if it was rotated 7 times.
Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].
Given the sorted rotated array nums of unique elements, return the minimum element of this array. You must write an algorithm that runs in O(log n) time.
Hint : Important thing to understand is that a[0] will be greater than a[n-1], and so play with that
class Solution {
public:
int findMin(vector<int>& nums) {
int n = nums.size();
if(n==1)
return nums[0];
int s=0;
int e=n-1;
int mid;
while(s<e){
if(nums[s] < nums[e])
return nums[s];
mid = s+ ((e-s)/2);
if(nums[mid] >= nums[s])
s = mid + 1;
else
e = mid;
}
return nums[s];
}
};
8. Search in Rotated Sorted Array
Problem There is an integer array nums sorted in ascending order (with distinct values).
Prior to being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].
Given the array nums after the rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.
You must write an algorithm with O(log n) runtime complexity.
Hint : Here we need to check whether the first or the 2nd part of the array is sorted or not and make the further sub divisions accordingly
class Solution {
public:
int search(vector<int>& nums, int target) {
int n = nums.size();
int l=0;
int r = n-1;
int mid;
while(l<=r){
mid = l + ((r-l)/2);
if(nums[mid]==target)
return mid;
if(nums[l] <= nums[mid])
{
if(nums[mid]>=target && target>=nums[l])
r=mid-1;
else
l = mid+1;
}
else{
if(nums[mid]<=target && nums[r]>=target)
l=mid+1;
else
r=mid-1;
}
}
return -1;
}
};
9. 3Sum
Problem 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.
Notice that the solution set must not contain duplicate triplets.
Hint : similar to 2 pointer method but we need to take care of duplicates
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
int n = (int)nums.size()-2;
vector<vector<int>> ans;
sort(nums.begin(),nums.end());
for(int i=0 ;i<(int)nums.size()-2; i++){
if(i==0 || (i>0 && nums[i-1]!=nums[i])){
int sum = 0 - nums[i];
int low = i+1;
int high =(int)nums.size()-1;
while(low<high){
if(nums[low]+nums[high]==sum){
ans.push_back({nums[i],nums[low],nums[high]});
while(low<high && nums[low]==nums[low+1]) low++;
while(low<high && nums[high]==nums[high-1]) high--;
low++;
high--;
}
else if(nums[low]+nums[high]<sum){
low++;
}
else{
high--;
}
}
}
}
return ans;
}
};
10. Container With Most Water
Problem Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis forms a container, such that the container contains the most water. Notice that you may not slant the container.
Hint : we can optimise the length and using 2 pointer and move in the direction which gives higher area while having the width high
class Solution {
public:
int maxArea(vector<int>& height) {
int w = height.size()-1;
int l =0;
int r = w;
int area=0;
int h;
while(l<r){
h = min(height[l],height[r]);
int temp = h * w;
area = max(area,temp);
if(height[l] < height[r])
l = l+1;
else
r = r-1;
w--;
}
return area;
}
};