DSA Sheet - Day 2 Arrays

DSA Sheet - Day 2 (Arrays)

🚀 DSA Sheet – Day 2: Arrays (Part 2)

Level up your array skills with medium-level interview problems. This set introduces powerful techniques like Kadane’s Algorithm, Two Pointers, and Dutch National Flag.

📌 Practice Problems

🧠 Key Approaches

  • Kadane’s Algorithm: Track current sum, reset when negative
  • Container With Most Water: Two pointer optimization
  • Sort 0s,1s,2s: Dutch National Flag Algorithm
  • 3Sum: Sorting + Two pointers
  • 4Sum: Extension of 3Sum with extra loop
  • Search in 2D Matrix: Binary search (treat as 1D)

⚡ Quick Cheatsheet

Kadane’s Algorithm


int maxSum = INT_MIN, curr = 0;
for(int x : nums){
  curr += x;
  maxSum = max(maxSum, curr);
  if(curr < 0) curr = 0;
}
    

Container With Most Water


int l = 0, r = n - 1, ans = 0;
while(l < r){
  ans = max(ans, min(h[l], h[r]) * (r - l));
  if(h[l] < h[r]) l++;
  else r--;
}
    

Sort Colors (Dutch National Flag)


int low = 0, mid = 0, high = n - 1;
while(mid <= high){
  if(nums[mid] == 0) swap(nums[low++], nums[mid++]);
  else if(nums[mid] == 1) mid++;
  else swap(nums[mid], nums[high--]);
}
    

3Sum


sort(nums.begin(), nums.end());
for(int i = 0; i < n; i++){
  int l = i + 1, r = n - 1;
  while(l < r){
    int sum = nums[i] + nums[l] + nums[r];
    if(sum == 0) { l++; r--; }
    else if(sum < 0) l++;
    else r--;
  }
}
    

Search in 2D Matrix


int l = 0, r = n * m - 1;
while(l <= r){
  int mid = (l + r) / 2;
  int val = matrix[mid / m][mid % m];
  if(val == target) return true;
  else if(val < target) l = mid + 1;
  else r = mid - 1;
}
    

🔥 Pro Tip

These problems introduce **core interview patterns**:
  • Two Pointer Technique
  • Greedy Decisions
  • Search Space Optimization
Master these and you’ll start solving medium problems much faster.
Continue Reading →