DSA
Concept-1: Arrays
Topic 1 — Two Pointers
Q1: Two Sum
Input : numbers = [2, 7, 11, 15], target = 9
Output: [1, 2]
class Solution {
public int[] twoSum(int[]numbers,int
target) {
int i = 0, j = [Link] - 1;
while (i < j) {
int sum = numbers[i] + numbers[j];
if (sum == target)
return new int[]{i + 1, j + 1};
else if (sum < target) i++;
else j--;
}
return new int[0]; }
}
Q2: Three Sum
Input : nums = [-1, 0, 1, 2, -1, -4]
Output: [[-1, -1, 2], [-1, 0, 1]]
class Solution {
public List<List<Integer>> threeSum(int[] nums)
{
[Link](nums);
List<List<Integer>> arr = new ArrayList<>();
for (int i = 0; i < [Link] - 2; i++) {
Page 1 of 5
if (i > 0 && nums[i] == nums[i - 1]) continue;
int left = i + 1,
right = [Link] - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
[Link]([Link](nums[i], nums[left],
nums[right]));
left++;
right--;
while (left < right && nums[left] == nums[left
- 1]) left++;
while (left < right && nums[right] ==
nums[right + 1]) right--;
}
else if (sum < 0) left++;
else right--; } }
return arr; }}
Q3: Sort Colors
Input : nums = [2, 0, 2, 1, 1, 0]
Output: [0, 0, 1, 1, 2, 2]
class Solution {
public void sortColors(int[]
nums) {
int low = 0, mid = 0,
high = [Link] - 1;
while (mid <= high) {
if (nums[mid] == 0) {
nums[mid] = nums[low];
nums[low] = 0;
low++; mid++; }
else if (nums[mid] == 1) {
mid++; }
else {
Page 2 of 5
nums[mid] = nums[high];
nums[high] = 2;
high--; }}}}
Q4: Move Zeroes
Input : nums = [0, 1, 0, 3, 12]
Output: [1, 3, 12, 0, 0]
class Solution {
public void
moveZeroes(int[] nums)
{ int i = 0, j = 0;
while (j < [Link])
{ if (nums[j] == 0) { j++;
} else {
int temp = nums[j];
nums[j] = nums[i];
nums[i] = temp;
i++; j++; }
}
}}
Q5: Container With Most Water
Input : height = [1, 8, 6, 2, 5, 4, 8, 3, 7]
Output: 49
class Solution {
public int maxArea(int[] height) {
int left = 0, right = [Link] - 1, maxArea
= 0;
while (left <= right) {
int area = [Link](height[left], height[right])
* (right - left);
maxArea = [Link](area, maxArea);
if (height[left] <= height[right]) left++;
else right--; }
Page 3 of 5
return maxArea; }
}
Topic 2 — Sliding Window
Q1: Maximum Sum Subarray of Size K
Input : arr[] = [100, 200, 300, 400], k = 2
Output: 700
class Solution {
public int maxSubarraySum(int[] arr,
int k) {
int n = [Link], windowSum = 0;
for (int i = 0; i < k; i+
+)windowSum+= arr[i];
int max = windowSum;
for (int j = k; j < n; j++)
{ windowSum += arr[j];
windowSum -= arr[j - k];
max = [Link](windowSum, max); }
return max; }
}
Q2: Max Consecutive Ones
Input : nums = [1, 1, 0, 1, 1, 1]
Output: 3
class Solution {
public int
findMaxConsecutiveOnes(int[] nums)
{
int count = 0, max = 0;
for (int i = 0; i < [Link]; i+
+){
if (nums[i] == 1) { count++; }
else {
Page 4 of 5
max = [Link](max, count);
count = 0; } }
return [Link](max, count); }
}
Page 5 of 5