0% found this document useful (0 votes)
4 views16 pages

Array (2)

The document contains Java code solutions for various array-related problems, including finding the largest and second largest elements, checking if an array is sorted and rotated, removing duplicates, and rotating arrays. It also includes methods for finding missing numbers, performing linear searches, and merging sorted arrays. Each solution is structured within a class and provides a clear algorithm for solving the respective problem.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views16 pages

Array (2)

The document contains Java code solutions for various array-related problems, including finding the largest and second largest elements, checking if an array is sorted and rotated, removing duplicates, and rotating arrays. It also includes methods for finding missing numbers, performing linear searches, and merging sorted arrays. Each solution is structured within a class and provides a clear algorithm for solving the respective problem.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ARRAY EASY QUESTIONS Class Solution {

Public int secondLargest(int[] nums) {


[Link] ELEMENT IN ARRAY Int max = Integer.MIN_VALUE;
Int secondMax = Integer.MIN_VALUE;
Class Solution { // First pass to find the largest element
Public int findLargest( int[] nums ) { For (int num : nums) {
Int max = nums[0]; // Assume first If (num > max) {
element is largest Max = num;
For (int I = 1; I < [Link]; i++) { }}
If (nums[i] > max) { // Second pass to find the secondlargest
Max = nums[i]; element
// Update max if current element is larger for (int num : nums) {
}} if (num > secondMax && num < max) {
Return max; secondMax = num;
}} }}
Optimal solution Return (secondMax ==
Integer.MIN_VALUE) ? -1 : secondMax;
Class Solution { }}
Public int findLargest(int[] nums) {
Optimized Solution
Int max = Integer.MIN_VALUE;
For (int num : nums) { Int small = Integer.MAX_VALUE;
If (num > max) { Int second_small = Integer.MAX_VALUE;
Max = num; Int large = Integer.MIN_VALUE;
}} Int second_large = Integer.MIN_VALUE;
Return max; For (int I = 0; I < n; i++)
}}
[Link] LARGEST ELEMENT IN ARRAY {
Small = [Link](small,arr[i]);
public class SecondLargest { Large = [Link](large,arr[i]);
public static void main(String[] args) { }
for (int I = 0;I < n;i++)
int[] arr = {12, 35, 1, 10, 34, 1}; {
int first = Integer.MIN_VALUE; if (arr[i] < second_small && arr[i] != small)
int second = Integer.MIN_VALUE; {
for (int num : arr) { Second_small = arr[i];
}
if (num > first) { if (arr[i] > second_large && arr[i] != large)
second = first; {
first = num; Second_large = arr[i];
}}
} else if (num > second && num != first) { [Link](“Second smallest is
second = num; “+second_small);
}} [Link](“Second largest is
Else if (second == Integer.MIN_VALUE) { “+second_large);
[Link]("No second largest }
element");
[Link] if Array Is Sorted and Rotated
} else {
[Link]("Largest:" + first); class TUF {
[Link]("Second Largest:" + second); static boolean isSorted(int arr[], int n) {
}}} for (int i = 0; i < n; i++) {
2nd method for (int j = i + 1; j < n; j++) {
if (arr[j] <arr[i]) public boolean containsDuplicate(int[] nums)
return false; {
}} HashSet<Integer> set = new HashSet<>();
return true;
} for (int num : nums) {
Optimised Solution if (![Link](num)) {
return true; // duplicate found
class TUF { }}
static boolean isSorted(int arr[], int n) { return false;
for (int i = 1; i < n; i++) { }}
if (arr[i] < arr[i - 1])
return false;
import [Link];
}
return true;
} class Solution {
public boolean containsDuplicate(int[] nums)
class Solution { {
public boolean check(int[] nums) { [Link](nums);
int n = [Link];
int count = 0; for (int i = 1; i < [Link]; i++) {
for (int i = 0; i < n; i++) { if (nums[i] == nums[i - 1]) {
if ( nums[i] > nums[(i + 1) % n] ) { return true;
}}
count++;
} return false;
if (count > 1) return false; }}
// More than 1 break → not sorted & rotated
} import [Link];
return true;
}} class Solution {
Example: nums = [3,4,5,1,2]: true public boolean containsDuplicate(int[] nums)
[1,2,3,4,5] is the original sorted array. {
You can rotate the array by x = 3 positions to return
begin on the element of value 3: [3,4,5,1,2]. [Link](nums).distinct().count() !=
[Link] Duplicates from Sorted Array [Link];
} }
class Solution {
[Link] ARRAY BY one place
public int removeDuplicates(int[] nums) {
if ([Link] == 0) return 0; class Solution {
int i = 0; public void rotate(int[] nums) {
for (int j = 1; j < [Link]; j++) {
if (nums[j] != nums[i]) { int n = [Link];// Store the first element
i++; int temp = nums[0];
nums[i] = nums[j]; // Shift all elements one step to the right
}} for (int i = n - 1; i > 0; i--) {
return i + 1; nums[i] = nums[i - 1];
}} }
Neetcode 250 Question 2: CONTAINS // Place the first element at the last position
DUPLICATE nums[n-1] = temp;
}}
import [Link]; [Link] ARRAY BY N times
class Solution {
class Solution { public void moveZeroes(int[] 5nums) {
public void rotate(int[] nums, int k) { int pointer = 0;

int n = [Link]; for (int i = 0; i < [Link]; i++) {


k %= n; //handle cases where k > n if (nums[i] != 0) {
//Swap non-zero element with left pointer
// Step 1: Reverse the whole array int temp = nums[pointer];
reverse(nums, 0, n - 1); nums[pointer] = nums[i];
// Step 2: Reverse first k elements nums[i] = temp;
reverse(nums, 0, k - 1); pointer++;
// Step 3: Reverse remaining n - k elements }}}}
reverse(nums, k, n - 1); Second option
}
private void reverse(int[] nums, int start, int class Solution {
end) { public void moveZeroes(int[] nums) {
while (start < end) { int left = 0;
// swap nums[start] and nums[end] // Move all non-zero elements to the front
int temp = nums[start]; for (int i = 0; i < [Link]; i++) {
nums[start] = nums[end]; if (nums[i] != 0) {
nums[end] = temp; nums[left] = nums[i];
start++; left++;
end--; }}
}}} // Fill the remaining with zeros
Second option while (left < [Link]) {
nums[left] = 0;
class Solution { left++;
}}}
public void rotate(int[] arr, int k) { [Link] Search
int n = [Link];
k = k % n; // In case k > n int search(int arr[],int n,int num) {
int d = n - k; // Convert right
rotation to equivalent left rotation int i;
for(i=0;i<n;i++)
// Step 1: Store first 'd' elements in temp {
int[] temp = new int[d]; if(arr[i]==num)
for (int i = 0; i < d; i++) { return i;
temp[i] = arr[i]; }
} return -1;
// Step 2: Shift remaining elements to the left }
for (int i = d; i < n; i++) { [Link]
arr[i - d] = arr[i];
} class Solution {
// Step 3: Copy temp elements to the end public static void main(String[] args) {
for (int i = n - d; i < n; i++) { int[] arr1 = {1, 2, 3, 4, 5};
arr[i] = temp[i - (n - d)]; int[] arr2 = {3, 4, 5, 6, 7};
}}} // Use Set to store unique elements
Set<Integer> unionSet = new HashSet<>();
[Link] ZEROES TO LAST OF ARRAY

Optimal Solution for (int num : arr1) {


[Link](num);
class Solution { }
for (int num : arr2) { }
[Link](num); else {
} count=0;
// Print Union }}
[Link]("Union of Arrays: " return maxi;
+unionSet); }}
}} [Link] the number that appears once, and
[Link] NUMBER other numbers twice.
Optimal Solution class Solution {
class Solution { public int singleNumber(int[] nums) {
public int missingNumber(int[] nums) { int n = [Link];
int n = [Link];
int actualSum= (n*(n+1))/2; for(int i=0 ;i<n ;i++) {
int sum=0; int num=nums[i];
for(int i=0;i<n ; i++){ int count=0;
sum= sum+nums[i]; for (int j = 0; j < n; j++) {
} if (arr[j] == num)
return actualSum -sum; count++;
}} }
// if the occurrence is 1 return ans:
if (count == 1) return num;
class Solution { //This line will never execute
public int missingNumber(int[] nums) { //if the array contains a single element.
int n = [Link]; return -1;
for (int i = 0; i <= n; i++) { }}
Optimal Solution
boolean found = false;
for (int j = 0; j < n; j++) { class Solution {
if (nums[j] == i) { public int singleNumber(int[] nums) {
found = true; int result = 0;
break; for (int num : nums) {
}} result = result ^ num; // XOR
if (!found) { operation
return i; }
}} return result;
return -1; // Should never reach here }}
}} Neetcode: Merge Sorted Array
11. MAXIMUM CONSECUTIVE ONES
class Solution {
class Solution { public void merge(int[] nums1, int m, int[]
public int findMaxConsecutiveOnes(int[] nums) nums2, int n) {
{ int i = m - 1; // last element in nums1
int j = n - 1; // last element in nums2
int size=[Link];
int k = m + n - 1; // last position in nums1
int count=0;
while (i >= 0 && j >= 0) {
int maxi=0;
if (nums1[i] > nums2[j]) {
for (int i=0;i<size;i++) {
nums1[k] = nums1[i];
if(nums[i]==1) { k--;
count++; i--;
maxi =[Link](maxi,count); } else {
nums1[k] = nums2[j]; 2nd method
k--;
j--; class Solution {
}} public int removeElement(int[] nums, int val) {
// Copy remaining nums2 elements int left = 0;
while (j >= 0) { int right = [Link] - 1;
nums1[k] = nums2[j];
k--;
while (left <= right) {
j--;
if (nums[left] == val) {
}}}
nums[left] = nums[right];
MEDIUM QUESTIONS right--;
} else {
Neetcode 250 Question 1: Concatenation left++;
of Array }}
return left;
class Solution { }}
public int[] getConcatenation(int[] nums) { Neetcode 250 Question 4: 2SUM
int n = [Link];
class Solution {
int [] ans = new int[2 * n];
public int[] twoSum(int[] nums, int target)
for (int i = 0; i < n; i++) { {
ans[i] = nums[i]; for (int i = 0; i < [Link]; i++) {
ans[i + n] = nums[i]; for (int j = i + 1; j < [Link]; j++) {
if (nums[i] + nums[j] == target) {
}
return new int[]{i, j};
return ans; }}}
}} return new int[]{};
2nd method }}

class Solution {
import [Link];
public int[] getConcatenation(int[] nums) {
public class Solution {
int n = [Link];
public int[] twoSum(int[] nums, int target){
int [] ans = new int [2 * n];
HashMap<Integer, Integer> map = new
HashMap<>(); // value -> index
for (int i = 0; i < 2 * n; i++) {
for (int i = 0; i < [Link]; i++) {
ans[i] = nums[i % n];
int complement = target - nums[i];
}
if ([Link](complement)) {
return ans;
return new int[] { [Link](complement), i };
}}
}
Neetcode 250 Question 7: Remove Element [Link](nums[i], i);
}
class Solution {
throw new IllegalArgumentException("No
public int removeElement(int[] nums, int val) {
two sum solution");
int k = 0; // index for valid elements
}}
for (int i = 0; i < [Link]; i++) {
if (nums[i] != val) {
nums[k] = nums[i]; class Solution {
k++; public int[] twoSum(int[] nums, int target){
}} HashMap<Integer, Integer> map = new
return k; HashMap<>();
}} for(int i =0; i< [Link]; i++){
int req = target-nums[i]; } else { // nums[mid] == 2
if([Link](req)){ swap(nums, mid, high);
int[] arr = {[Link](req) , i}; high--;
return arr; }}}
} private void swap(int[] nums, int i, int j) {
[Link](nums[i], i); int temp = nums[i];
} nums[i] = nums[j];
return new int[]{-1, -1}; nums[j] = temp;
}} }}
Neetcode 250 Question 12: SORT 0’s 1’s 2’s Neetcode 250 Question 8: MAJORITY
in array ELEMENT
Example 1: Example: nums = [2,2,1,1,1,2,2] output:2
Output:
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2] class Solution {
public int majorityElement(int[] nums) {
Example 2: int n=[Link];

Input: nums = [2,0,1] for(int i=0;i<n;i++){


Output: [0,1,2] int count=0;
for(int j=0;j<n;j++){
class Solution {
if(nums[j]==nums[i])
public void sortColors(int[] nums) {
{
int count0 = 0, count1 = 0, count2 = 0;
count++;
}}
// Count the number of 0s, 1s, and 2s
if(count >n/2){
for (int num : nums) {
return nums[i];
if (num == 0) count0++;
}}
else if (num == 1) count1++;
return -1;
else count2++;
}}
}
// Overwrite the array based on counts
Optimised solution
int index = 0; class Solution {
public int majorityElement(int[] nums) {
while (count0-- > 0) nums[index++] = 0; int count = 0;
while (count1-- > 0) nums[index++] = 1; int candidate = 0;
while (count2-- > 0) nums[index++] = 2; for (int num : nums) {
}} if (count == 0) {
Optimised solution candidate = num;
class Solution { }
public void sortColors(int[] nums) { count += (num == candidate) ? 1 : -1;
int low = 0, mid = 0, high = [Link] - 1; }
return candidate;
while (mid <= high) { }}
if (nums[mid] == 0) {
KADANE ‘S MAXIMUM SUBARRAY SUM
swap(nums, low, mid);
low++; Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
mid++; Output: 6
} else if (nums[mid] == 1) { Explanation: The subarray [4,-1,2,1] has the
mid++; largest sum 6.
class Solution { Stock Buy and Sell
public int maxSubArray(int[] nums) {
int maxSum = Integer.MIN_VALUE; // to store max class Solution {
sum public int maxProfit(int[] prices) {
int n = [Link]; int maxProfit = 0;
int n = [Link];
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) { // Buy day
int currentSum = 0; for (int j = i + 1; j < n; j++) { // Sell
for (int j = i; j < n; j++) { day after buy day
currentSum += nums[j]; int profit = prices[j] - prices[i];
// sum of subarray from i to j maxProfit = [Link](maxProfit, profit);
maxSum = [Link](maxSum, currentSum); }}
}} return maxProfit;
return maxSum; }}
}} Optimised solution
Optimised solution
class Solution {
class Solution { public int maxProfit(int[] prices) {
public int maxSubArray(int[] nums) { int minPrice = Integer.MAX_VALUE;
int maxSum = nums[0];// Initialize with int maxProfit = 0;
first element
int currentSum = 0; for (int price : prices) {
if (price < minPrice) {
for (int num : nums) { minPrice = price;
currentSum += num; // Add current number to // update the lowest price seen so far
sum } else {
maxSum = [Link](maxSum, currentSum); maxProfit = [Link](maxProfit, price -
// Update max if needed minPrice); // potential profit
if (currentSum < 0) { }}
currentSum = 0; // Reset if sum is return maxProfit;
negative }}
}} NEETCODE 19: Stock Buy and Sell 2
return maxSum;
}} class TUF {
static boolean isSorted(int arr[], int n) {
KADANES
for (int i = 0; i < n; i++) {
class Solution { for (int j = i + 1; j < n; j++) {
public int maxSubArray(int[] nums) {
int currentSum = nums[0]; if (arr[j] <arr[i])
int maxSum = nums[0]; return false;
for (int i = 1; i < [Link]; i++) { }}
// Either start new subarray or extend the return true;
existing one }
currentSum = [Link](nums[i], currentSum +
nums[i]);
class Solution {
public int maxProfit(int[] prices) {
// Update max if current is better
int profit = 0;
maxSum = [Link](maxSum, currentSum);
}
for (int i = 1; i < [Link]; i++) {
return maxSum;
if (prices[i] > prices[i - 1]) {
}}
profit += prices[i] - prices[i - 1]; Input: nums = [100,4,200,1,3,2]
}} Output: 4
return profit; Explanation: The longest consecutive elements
}} sequence is [1, 2, 3, 4]. Therefore its length
Rearrange the array in alternating positive and is 4.
negative items
Optimised Solution
class Solution {
import [Link];
public int[] rearrangeArray(int[] nums) {
class Solution {
int result[] = new int[[Link] ];
public int longestConsecutive(int[] nums) {
int positive=0;
HashSet<Integer> set = new HashSet<>();
int negative=1;
for (int num : nums) {
[Link](num); }
for(int i=0;i<[Link];i++){
// Add all elements to the HashSet
if(nums[i]>0){
int longestStreak = 0;
result[positive]=nums[i];
for (int num : set) {
positive=positive+2;
// Check if it's the start of a sequence
}
if (![Link](num - 1)) {
else{
int currentNum = num ;
result[negative]=nums[i];
int currentStreak = 1 ;
negative=negative+2;
// Count consecutive elements
}}
while ([Link](currentNum + 1)) {
return result;
currentNum++;
}}
currentStreak++;
Leaders in array }
longestStreak = [Link](longestStreak,
An element is a leader if it is greater than or equal to
currentStreak);
all elements to its right. }
return longestStreak;
import [Link].*;
}}
public class Solution {
public List<Integer> findLeaders(int[] arr) { SET MATRIX ZEROES
List<Integer> leaders = new ArrayList<>(); class Solution {
int n = [Link]; public void setZeroes(int[][] matrix) {
int rows = [Link];
int maxFromRight = arr[n - 1]; int cols = matrix[0].length;
[Link](maxFromRight); // Rightmost
element is always a leader // First pass: mark rows and columns
// Traverse from second last to the beginning for (int i = 0; i < rows; i++) {
for (int i = n - 2; i >= 0; i--) { for (int j = 0; j < cols; j++) {
if (arr[i] > maxFromRight) { if (matrix[i][j] == 0) {
maxFromRight = arr[i]; markRow(matrix, i);
[Link](maxFromRight); markCol(matrix, j);
}} }}}
// Leaders collected in reverse order, reverse // Second pass: convert all -1 to 0
to maintain original order for (int i = 0; i < rows; i++) {
[Link](leaders); for (int j = 0; j < cols; j++) {
return leaders; if (matrix[i][j] == -1) {
}} matrix[i][j] = 0;
Longest Consecutive Sequence }}}}
private void markRow(int[][] matrix, int row){
for (int j = 0; j < matrix[0].length; j++){ }}}
if (matrix[row][j] != 0) { // Step 2: Use the markers to update the cells
matrix[row][j] = -1; // mark (except first row and col)
}}} for (int i = 1; i < rows; i++) {
private void markCol(int[][] matrix, int col){ for (int j = 1; j < cols; j++) {
for (int i = 0; i < [Link]; i++) { if (matrix[i][0] == 0 || matrix[0][j] == 0)
if (matrix[i][col] != 0) { {
matrix[i][col] = -1; // mark matrix[i][j] = 0;
}}}} }}}
// Step 3: Update the first row if needed
if (matrix[0][0] == 0) {
class Solution { for (int j = 1; j < cols; j++) {
public void setZeroes(int[][] matrix) { matrix[0][j] = 0;
int rows = [Link]; }}
int cols = matrix[0].length;
// Step 4: Update the first column if needed
int[] row = new int[rows]; // default 0 if (col0 == 0) {
int[] col = new int[cols]; // default 0 for (int i = 0; i < rows; i++) {
matrix[i][0] = 0;
// Step 1: Mark rows and columns }}}}
for (int i = 0; i < rows; i++) {
Neetcode 21: Subarray Sum Equals K
for (int j = 0; j < cols; j++) {
if (matrix[i][j] == 0) {
Brute force method :
row[i] = 1;
col[j] = 1; class Solution {
}}} public int subarraySum(int[] nums, int k) {
// Step 2: Set matrix cells to 0 if int count = 0;
their row or column is marked for (int i = 0; i < [Link]; i++) {
for (int i = 0; i < rows; i++) { int sum = 0;
for (int j = 0; j < cols; j++) { for (int j = i; j < [Link]; j++) {
if (row[i] == 1 || col[j] == 1) { sum += nums[j];
matrix[i][j] = 0; if (sum == k) {
}}}} count++;
}}}
Optimised solution return count;
}}
class Solution {
public void setZeroes(int[][] matrix) { Optimised method :
int rows = [Link];
import [Link];
int cols = matrix[0].length; class Solution {
int col0 = 1; // Track whether the public int subarraySum(int[] nums, int k) {
first column needs to be zeroed
HashMap<Integer, Integer> map = new HashMap<>();
// Step 1: Mark the first row, column, and col0
[Link](0, 1); // important base case
based on zero positions
for (int i = 0; i < rows; i++) {
int sum = 0;
if (matrix[i][0] == 0) col0 = 0; // first
int count = 0;
column marker
for (int j = 1; j < cols; j++) {
if (matrix[i][j] == 0) { for (int num : nums) {
matrix[i][0] = 0; // mark row sum += num;
matrix[0][j] = 0; // mark column // check if (sum - k) exists
if ([Link](sum - k)) { }
count += [Link](sum - k); // Step 2: Fill right array
} right[[Link] - 1] = 1;
// store prefix sum frequency for (int i = [Link] - 2; i >= 0; i--) {
[Link](sum, [Link](sum, 0) + 1); right[i] = right[i + 1] * nums[i + 1];
} }
return count; // Step 3: Multiply left and right arrays to get answer
} } int[] ans = new int[[Link]];
for (int i = 0; i < [Link]; i++) {
Neetcode 13 : Top K Frequent Elements
ans[i] = left[i] * right[i];
import [Link].*; }
class Solution { return ans;
public int[] topKFrequent(int[] nums, int k) { }}
// Step 1: Count frequency 2nd method :
HashMap<Integer,Integer>freqMap=new HashMap<>();
for (int num : nums) { class Solution {
[Link](num, public int[] productExceptSelf(int[] nums) {
[Link](num, 0) + 1);
} int n = [Link];
// Step 2: Bucket array (index = frequency) int[] answer = new int[n];
List<Integer>[] bucket = new // Step 1: Left products
List[[Link] + 1]; answer[0] = 1;
for (int key : [Link]()) { for (int i = 1; i < n; i++) {
int freq = [Link](key); answer[i] = answer[i - 1] * nums[i - 1];
if (bucket[freq] == null) { }
bucket[freq] = new ArrayList<>(); // Step 2: Right products
} int rightProduct = 1;
bucket[freq].add(key); for (int i = n - 1; i >= 0; i--) {
} answer[i] = answer[i] * rightProduct;
// Step 3: Collect top k frequent elements rightProduct *= nums[i];
int[] result = new int[k]; }
int index = 0; return answer;
for (int i = [Link] - 1; i >= 0 && }}
index < k; i--) {
Neetcode 17 : Valid Sudoku
if (bucket[i] != null) {
for (int num : bucket[i]) { class Solution {
result[index++] = num; public boolean isValidSudoku(char[][] board) {
if (index == k) break;
}}}
HashSet<Character>[] rows = new HashSet[9];
return result;
HashSet<Character>[] cols = new HashSet[9];
}}
HashSet<Character>[] boxes = new HashSet[9];
Neetcode 16 : Product of Array Except Self
public class Solution { for (int i = 0; i < 9; i++) {
public int[] productExceptSelf(int[] nums) { rows[i] = new HashSet<>();
// Array to store all left multiplications cols[i] = new HashSet<>();
int[] left = new int[[Link]]; boxes[i] = new HashSet<>();
// Array to store all right multiplications }
int[] right = new int[[Link]]; for (int r = 0; r < 9; r++) {
// Step 1: Fill left array for (int c = 0; c < 9; c++) {
left[0] = 1; char val = board[r][c];
for (int i = 1; i < [Link]; i++) { if (val == '.') continue;
left[i] = left[i - 1] * nums[i - 1]; // Check row
if (rows[r].contains(val)) return false;
rows[r].add(val); matrix[i][left] = matrix[i][right];
matrix[i][right] = temp;
// Check column left++;
if (cols[c].contains(val)) return false; right--;
cols[c].add(val); }}}}
Count subarrays with given sum
// Check box
class Solution {
int boxIndex = (r / 3) * 3 + (c / 3);
public int subarraySum(int[] nums, int k) {
if (boxes[boxIndex].contains(val)) return false;
int count = 0;
boxes[boxIndex].add(val);
for (int i = 0; i < [Link]; i++) {
}}
int sum = 0;
return true;
for (int j = i; j < [Link]; j++) {
}}
sum += nums[j];
if (sum == k) {
count++;
ROTATE IMAGE
}}}
class Solution { return count;
public void rotate(int[][] matrix) { }}
int n = [Link]; HARD PROBLEMS
int[][] temp = new int[n][n]; // extra
matrix PASCAL TRIANGLE
// Copy elements to temp in rotated position
for (int i = 0; i < n; i++) { [Link] the value of element by number of row
for (int j = 0; j < n; j++) { and column
temp[j][n - 1 - i] = matrix[i][j];
}} public class Pascal {
// Copy back to original matrix
for (int i = 0; i < n; i++) { // Function to calculate nCr efficiently
for (int j = 0; j < n; j++) { public static long nCr(int n, int r) {
matrix[i][j] = temp[i][j]; long res = 1;
}}}}
Optimised solution // Since C(n, r) = C(n, n - r)
if (r > n - r)
class Solution { r = n - r;
public void rotate(int[][] matrix) {
int n = [Link]; for (int i = 0; i < r; i++) {
// Step 1: Transpose the matrix res = res * (n - i);
for (int i = 0; i < n; i++) { res = res / (i + 1);
for (int j = i + 1; j < n; j++) { }
// Swap matrix[i][j] with matrix[j][i] return res;
int temp = matrix[i][j]; }
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp; public static int pascalTriangle(int r, int c)
}} {
// Step 2: Reverse each row int element = (int) nCr(r - 1, c - 1);
for (int i = 0; i < n; i++) { return element;
int left = 0, right = n - 1; }
while (left < right) { R=5,C=3 5*4*3/3*2*1 =6
// Swap matrix[i][left] and matrix[i][right]
int temp = matrix[i][left]; [Link] elements in row
public class Main { public List<List<Integer>> generate(int
public static long nCr(int n, int r) { numRows) {
long res = 1; List<List<Integer>> triangle = new
// calculating nCr: ArrayList<>();
for (int i = 0; i < r; i++) {
res = res * (n - i); for (int row = 0; row < numRows; row++)
res = res / (i + 1); {
} List<Integer> currentRow = new
return res; ArrayList<>();
} [Link](1); // first element is
public static void pascalTriangle(int n) { always 1
// printing the entire row n: // Fill the middle elements based on previous
for (int c = 1; c <= n; c++) { row
[Link](nCr(n - 1, c - 1) + " "); for (int col = 1; col < row; col++)
} {
[Link](); int val = [Link](row - 1).get(col - 1)
} + [Link](row - 1).get(col);
[Link](val);
}
public class Solution {
if (row > 0) {
// Helper function to calculate nCr [Link](1);
public int nCr(int n, int r) { // last element is also 1 if row > 0
long res = 1; }

for (int i = 0; i < r; i++) { [Link](currentRow);


res = res * (n - i); }
res = res / (i + 1); return triangle;
} }}
return (int) res; Neetcode 250 Question 2: Majority Elements(N/3
}
times)
// Main function to generate Pascal's Triangle
public List<List<Integer>> generate(int class Solution {
numRows) { public List<Integer> majorityElement(int[]
List<List<Integer>> ans = new ArrayList<>(); nums) {
int n = [Link];
for (int row = 1; row <= numRows; row++) { List<Integer> result = new
List<Integer> tempList = new ArrayList<>(); ArrayList<>();
for (int col = 1; col <= row; col++) { for (int i = 0; i < n; i++) {
[Link](nCr(row - 1, col - 1)); // Skip if nums[i] is already in result
} if ([Link]() == 0 ||
[Link](tempList); [Link](0) != nums[i]) {
} if ([Link]() == 2 &&
return ans; [Link](1) == nums[i]) continue;
}}
Optimal Solution int count = 0;
for (int j = 0; j < n; j++) {
import [Link].*;
if (nums[j] == nums[i]) {
count++;
public class Solution { }}
if (count > n / 3) {
[Link](nums[i]); } else if (count2 == 0 && num != candidate1)
}} {
if ([Link]() == 2) break; count2 = 1;
} candidate2 = num;
return result; } else if (num == candidate1) {
}} count1++;
} else if (num == candidate2) {
import [Link].*; count2++;
class Solution { } else {
public List<Integer> majorityElement(int[] count1--;
nums) { count2--;
int n = [Link]; }}
List<Integer> result = new // 2nd pass: Verify actual counts
ArrayList<>(); count1 = 0;
count2 = 0;
for (int i = 0; i < n; i++) { for (int num : nums) {
// Skip if nums[i] is already in if (num == candidate1) count1++;
result else if (num == candidate2) count2++;
if ([Link]() == 0 || }
[Link](0) != nums[i]) {
if ([Link]() == 2 && List<Integer> result = new ArrayList<>();
[Link](1) == nums[i]) continue; int threshold = n / 3;

int count = 0; if (count1 > threshold)


for (int j = 0; j < n; j++) { [Link](candidate1);
if (nums[j] == nums[i]) { if (count2 > threshold)
count++; [Link](candidate2);
}}
if (count > n / 3) { return result;
[Link](nums[i]); }}
}} 3 SUM
if ([Link]() == 2) break;
} class Solution {
return result; public List<List<Integer>> threeSum(int[]
}} nums) {
Optimal Solution int n = [Link];
Set<List<Integer>> set = new HashSet<>();
class Solution {
public List<Integer> majorityElement(int[] // Try every triplet combination
nums) { for (int i = 0; i < n; i++) {
int n = [Link]; for (int j = i + 1; j < n; j++) {
int count1 = 0, count2 = 0; for (int k = j + 1; k < n; k++) {
int candidate1 = Integer.MIN_VALUE, if (nums[i] + nums[j] + nums[k] == 0) {
candidate2 = Integer.MIN_VALUE; List<Integer> triplet =
[Link](nums[i], nums[j], nums[k]);
// 1st pass: Find potential candidates
for (int num : nums) { [Link](triplet); // Sort to avoid
if (count1 == 0 && num != candidate2) { duplicate permutations
count1 = 1; [Link](triplet); // Set automatically
candidate1 = num; handles duplicates
}}}}
return new ArrayList<>(set);
}} [Link]([Link](nums[i], nums[j],
nums[k]));
j++;
class Solution { k--;
public List<List<Integer>> threeSum(int[]
nums) { //Skip duplicates for second and third numbers
int n = [Link]; while (j < k && nums[j] == nums[j - 1]) j++;
Set<List<Integer>> st = new HashSet<>(); while (j < k && nums[k] == nums[k + 1]) k--;
for (int i = 0; i < n; i++) { }}}
Set<Integer> hashset = new HashSet<>(); return ans;
for (int j = i + 1; j < n; j++) { }
int third = -(nums[i] + nums[j]); Largest Subarray with 0 Sum
if ([Link](third)) {
List<Integer> temp = [Link](nums[i], Optimal Solution
nums[j], third);
[Link](temp); int maxLen(int A[], int n)
[Link](temp); {
} // Your code here
[Link](nums[j]); HashMap<Integer, Integer> mpp = new
}} HashMap<Integer, Integer>();
return new ArrayList<>(st); int maxi = 0;
}} int sum = 0;
Optimal Solution
for(int i = 0;i<n;i++) {
import [Link].*; sum += A[i];
if(sum == 0) {
class Solution { maxi = i + 1;
public List<List<Integer>> threeSum(int[] }
nums) { else {
List<List<Integer>> ans = new if([Link](sum) != null) {
ArrayList<>();
[Link](nums); maxi = [Link](maxi, i - [Link](sum));
int n = [Link]; }
else {
for (int i = 0; i < n; i++) { [Link](sum, i);
// Skip duplicates for the first number }}}
if (i > 0 && nums[i] == nums[i - 1]) return maxi;
continue; }

int j = i + 1;
int k = n - 1; class Solution {
public int maxLengthZeroSumSubarray(int[]
while (j < k) { nums) {
int sum = nums[i] + nums[j] + nums[k]; int max = 0;
int n = [Link];
if (sum < 0) { for (int i = 0; i < n; ++i) {
j++; int sum = 0;
} else if (sum > 0) { for (int j = i; j < n; ++j) {
k--; sum += nums[j];
} else { if (sum == 0) {
max = [Link](max, j - i + 1);
}
}
}
return max;
}
}
Count number of subarrays with given xor K Map<Integer, Integer> mpp = new
HashMap<>(); //declaring the map.
class Solution { [Link](xr, 1); //setting the value of
public int subarraysWithXorK(int[] nums, 0.
int k) { int cnt = 0;
int count = 0;
int n = [Link]; for (int i = 0; i < n; i++) {
// prefix XOR till index i:
for (int i = 0; i < n; i++) { xr = xr ^ a[i];
for (int j = i; j < n; j++) {
int xor = 0; //By formula: x = xr^k:
for (int l = i; l <= j; l++) { int x = xr ^ k;
xor ^= nums[l];
} // add the occurrence of xr^k
if (xor == k) count++; // to the count:
}} if ([Link](x)) {
return count; cnt += [Link](x);
}} }

public class tUf { // Insert the prefix xor till index i


// into the map:
public static int subarraysWithXorK(int if ([Link](xr)) {
[]a, int k) { [Link](xr, [Link](xr) + 1);
int n = [Link]; } else {
//size of the given array. [Link](xr, 1);
int cnt = 0; }
}
return cnt;
// Step 1: Generating subarrays:
}
for (int i = 0; i < n; i++) {
int xorr = 0;
for (int j = i; j < n; j++) {

//step 2:calculate XOR of all


// elements:
xorr = xorr ^ a[j];

// step 3:check XOR and count:


if (xorr == k) cnt++;
}}
return cnt;
}

public class tUf {

public static int subarraysWithXorK(int


[]a, int k) {
int n = [Link]; //size of the given
array.
int xr = 0;

You might also like