0% found this document useful (0 votes)
3 views14 pages

Array (1)

The document provides various algorithms for array manipulation, including finding the largest and second largest elements, checking if an array is sorted and rotated, rotating arrays, removing duplicates, and performing linear searches. It also covers advanced topics like majority elements, maximum subarray sums using Kadane's algorithm, and stock buy and sell strategies. Each algorithm is presented with code snippets and explanations for clarity.
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)
3 views14 pages

Array (1)

The document provides various algorithms for array manipulation, including finding the largest and second largest elements, checking if an array is sorted and rotated, rotating arrays, removing duplicates, and performing linear searches. It also covers advanced topics like majority elements, maximum subarray sums using Kadane's algorithm, and stock buy and sell strategies. Each algorithm is presented with code snippets and explanations for clarity.
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 int first = Integer.MIN_VALUE;

[Link] ELEMENT IN ARRAY int second = Integer.MIN_VALUE;

Class Solution {

Public int findLargest( int[] nums ) { for (int num : arr) {

Int max = nums[0]; // Assume first element is if (num > first) {


largest
second = first;
For (int I = 1; I < [Link]; i++) {
first = num;
If (nums[i] > max) {
} else if (num > second && num != first) {
Max = nums[i]; // Update max if current
second = num;
element is larger
}}
}}
if (second == Integer.MIN_VALUE) {
Return max;
[Link]("No second largest
}}
element");
Optimal solution
} else {
Class Solution {
[Link]("Largest: " + first);
Public int findLargest(int[] nums) {
[Link]("Second Largest: " +
Int max = Integer.MIN_VALUE; second);

For (int num : nums) { } }}

If (num > max) { 2nd

Max = num; Class Solution {

}} Public int secondLargest(int[] nums) {

Return max; Int max = Integer.MIN_VALUE;

}} Int secondMax = Integer.MIN_VALUE;

[Link] LARGEST ELEMENT IN ARRAY // First pass to find the largest element

public class SecondLargest { For (int num : nums) {

public static void main(String[] args) { If (num > max) {

int[] arr = {12, 35, 1, 10, 34, 1}; Max = num;


}} Second_large = arr[i];

// Second pass to find the second largest }}


element
[Link](“Second smallest is
For (int num : nums) { “+second_small);

If (num > secondMax && num < max) { [Link](“Second largest is


“+second_large);
secondMax = num;
}
}}
[Link] if Array Is Sorted and Rotated
Return (secondMax == Integer.MIN_VALUE) ? -
1 : secondMax;
class TUF {
}} static boolean isSorted(int
Optimized Solution arr[], int n) {
for (int i = 0; i < n;
Int small = Integer.MAX_VALUE;
i++){
Int second_small = Integer.MAX_VALUE; for (int j = i + 1; j < n;
Int large = Integer.MIN_VALUE; j++){
if (arr[j] <arr[i])
Int second_large = Integer.MIN_VALUE;
return false;
For (int I = 0;I < n;i++) }}
{ return true;
}
Small = [Link](small,arr[i]);

Large = [Link](large,arr[i]);
Optimised Solution
}
class TUF {
For (int I = 0;I < n;i++)
static boolean isSorted(int arr[], int n) {
{
for (int i = 1; i < n; i++) {
If (arr[i] < second_small && arr[i] != small)
if (arr[i] < arr[i - 1]).
{
return false;
Second_small = arr[i];
}
}
return true;
If (arr[i] > second_large && arr[i] != large)
}
{
i++;
nums[i] = nums[j];
}}
return i + 1;
}}
class Solution { [Link] ARRAY BY one place
public boolean check(int[] nums) { class Solution {

int n = [Link]; public void rotate(int[] nums) {

int count = 0;
int n = [Link];
// Store the first element
int temp = nums[0];
for (int i = 0; i < n; i++) { // Shift all elements one step to the right

if (nums[i] > nums[(i + 1) % n]) { for (int i = n - 1; i > 0; i--) {


nums[i] = nums[i - 1];
count++; }
// Place the first element at the last position
} nums[n-1] = temp;
}}
if (count > 1) return false; // More than 1 break → [Link] ARRAY BY N times
not sorted & rotated
class Solution {
}
public void rotate(int[] nums, int k) {
return true;
int n = [Link];
}} k %= n; //handle cases where k > n

Example: nums = [3,4,5,1,2]: true


// Step 1: Reverse the whole array
[1,2,3,4,5] is the original sorted array. reverse(nums, 0, n - 1);
You can rotate the array by x = 3 // Step 2: Reverse first k elements
positions to begin on the element of reverse(nums, 0, k - 1);
// Step 3: Reverse remaining n - k elements
value 3: [3,4,5,1,2].
reverse(nums, k, n - 1);
[Link] Duplicates from Sorted Array }
private void reverse(int[] nums, int start, int end)
class Solution { {
public int removeDuplicates(int[] nums) while (start < end) {
// swap nums[start] and nums[end]
{
if ([Link] == 0) return 0;
int temp = nums[start];
nums[start] = nums[end];
int i = 0; nums[end] = temp;
start++;
end--;
for (int j = 1; j < [Link]; j++) {
}}}
if (nums[j] != nums[i]) { Second option
class Solution { int left = 0;
// Move all non-zero elements to the front
public void rotate(int[] arr, int k) { for (int i = 0; i < [Link]; i++) {
int n = [Link]; if (nums[i] != 0) {
k = k % n; // In case k > n nums[left] = nums[i];
int d = n - k; // Convert right rotation to left++;
equivalent left rotation }}
// Fill the remaining with zeros

// Step 1: Store first 'd' elements in temp


int[] temp = new int[d]; while (left < [Link]) {
for (int i = 0; i < d; i++) { nums[left] = 0;
temp[i] = arr[i]; left++;
} }}}
// Step 2: Shift remaining elements to the left [Link] Search
for (int i = d; i < n; i++) {
arr[i - d] = arr[i]; int search(int arr[],int n,int num) {
}
// Step 3: Copy temp elements to the end int i;
for(i=0;i<n;i++)
for (int i = n - d; i < n; i++) { {
if(arr[i]==num)
return i;
arr[i] = temp[i - (n - d)]; }
}}} return -1;
}
[Link]
[Link] ZEROES TO LAST OF ARRAY
class Solution {
Optimal Solution public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5};
class Solution { int[] arr2 = {3, 4, 5, 6, 7};
public void moveZeroes(int[] nums) {
int pointer = 0; // Use Set to store unique elements
Set<Integer> unionSet = new HashSet<>();

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


for (int num : arr1) {
if (nums[i] != 0) {
[Link](num);
// Swap non-zero element with left }
pointer for (int num : arr2) {
int temp = nums[pointer]; [Link](num);
}
nums[pointer] = nums[i]; // Print Union
nums[i] = temp; [Link]("Union of Arrays: " +
unionSet);
}}
pointer++;
}}}} 8. Remove Duplicates from Sorted Array

class Solution {
Second option public int removeDuplicates(int[]
class Solution { nums) {
public void moveZeroes(int[] nums) { if ([Link] == 0) return 0;
}}
int i = 0; 11. MAXIMUM CONSECUTIVE ONES
class Solution {
for (int j = 1; j < [Link]; public int findMaxConsecutiveOnes(int[] nums) {
j++) { int size=[Link];
int count=0;
if (nums[j] != nums[i]) {
int maxi=0;
i++; for (int i=0;i<size;i++) {
nums[i] = nums[j]; if(nums[i]==1) {
} count++;
maxi =[Link](maxi,count);
}
}
else {
return i + 1; count=0;
} }}
return maxi;
} }}
[Link] NUMBER [Link] the number that appears once, and
Optimal Solution other numbers twice.

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;
for (int j = 0; j < n; j++) {
sum= sum+nums[i];
if (arr[j] == num)
} count++;
return actualSum -sum; }
}} // if the occurrence is 1 return ans:
if (count == 1) return num;
class Solution { //This line will never execute
//if the array contains a single element.
return -1;
public int missingNumber(int[] nums) { }}
int n = [Link];
for (int i = 0; i <= n; i++) {
Optimal Solution
class Solution {
boolean found = false; public int singleNumber(int[] nums) {
for (int j = 0; j < n; j++) { int result = 0;
for (int num : nums) {
if (nums[j] == i) { result = result ^ num; // XOR operation
found = true; }
break; return result;
}} }}
if (!found) { MEDIUM QUESTIONS
return i;
}} 2SUM
return -1; // Should never reach here
class Solution {
public int[] twoSum(int[] nums, int target) { while (count0-- > 0) nums[index++] = 0;
for (int i = 0; i < [Link]; i++) { while (count1-- > 0) nums[index++] = 1;
for (int j = i + 1; j < [Link]; j++) { while (count2-- > 0) nums[index++] = 2;
if (nums[i] + nums[j] == target) { }}
return new int[]{i, j};
Optimised solution
}}}
return new int[]{}; public class SortColors {
}} public void sortColors(int[] nums) {
int low = 0, mid = 0, high = [Link] - 1;

import [Link];
while (mid <= high) {
if (nums[mid] == 0) {
public class Solution { // Swap nums[low] and nums[mid]
public int[] twoSum(int[] nums, int target) { int temp = nums[low];
HashMap<Integer, Integer> map = new HashMap<>(); // nums[low] = nums[mid];
value -> index nums[mid] = temp;
for (int i = 0; i < [Link]; i++) { low++;
int complement = target - nums[i]; mid++;
if ([Link](complement)) { } else if (nums[mid] == 1) {
return new int[] { [Link](complement), i }; mid++;
} } else {
[Link](nums[i], i); // nums[mid] == 2
} // Swap nums[mid] and nums[high]
throw new IllegalArgumentException("No two int temp = nums[mid];
sum solution"); nums[mid] = nums[high];
}} nums[high] = temp;
SORT 0’s 1’s 2’s in array high--;
}}}}
Example 1:

Input: nums = [2,0,2,1,1,0] MAJORITY ELEMENT


Output: [0,0,1,1,2,2]
Example: nums = [2,2,1,1,1,2,2] output:2
Example 2:
Output:
Input: nums = [2,0,1] class Solution {
Output: [0,1,2] public int majorityElement(int[] nums) {
int n=[Link];
class Solution {
public void sortColors(int[] nums) {
for(int i=0;i<n;i++){
int count0 = 0, count1 = 0, count2 = 0;
int count=0;
for(int j=0;j<n;j++){
// Count the number of 0s, 1s, and 2s if(nums[j]==nums[j])
for (int num : nums) { {
if (num == 0) count0++; count++;
else if (num == 1) count1++; }}
else count2++; if(count >n/2){
} return nums[i];
}}
// Overwrite the array based on counts return -1;
int index = 0; }}
Optimised solution class Solution {
public int maxSubArray(int[] nums) {
class Solution { int currentSum = nums[0];
public int majorityElement(int[] nums) { int maxSum = nums[0];
int count = 0;
int candidate = 0; for (int i = 1; i < [Link]; i++) {
for (int num : nums) { // Either start new subarray or extend
if (count == 0) { the existing one
candidate = num; currentSum = [Link](nums[i], currentSum +
} nums[i]);
count += (num == candidate) ? 1 : -1;
}
return candidate; // Update max if current is better
}} maxSum = [Link](maxSum, currentSum);
}
KADANE ‘S MAXIMUM SUBARRAY SUM return maxSum;
}}
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Stock Buy and Sell
Output: 6
Explanation: The subarray [4,-1,2,1] has the class Solution {
largest sum 6. public int maxProfit(int[] prices) {
int maxProfit = 0;
class Solution { int n = [Link];
public int maxSubArray(int[] nums) {
int maxSum = Integer.MIN_VALUE; // to store max sum
int n = [Link]; for (int i = 0; i < n; i++) { // Buy day
for (int j = i + 1; j < n; j++) { //
Sell day after buy day
for (int i = 0; i < n; i++) { int profit = prices[j] - prices[i];
int currentSum = 0; maxProfit = [Link](maxProfit, profit);
for (int j = i; j < n; j++) { }}
currentSum += nums[j]; // sum of return maxProfit;
subarray from i to j }}
maxSum = [Link](maxSum, currentSum);
}}
Optimised solution
return maxSum; class Solution {
}} public int maxProfit(int[] prices) {
Optimised solution int minPrice = Integer.MAX_VALUE;
int maxProfit = 0;
class Solution {
public int maxSubArray(int[] nums) {
int maxSum = nums[0];// Initialize with for (int price : prices) {
first element if (price < minPrice) {
int currentSum = 0; minPrice = price; // update the
lowest price seen so far
for (int num : nums) { } else {
currentSum += num; // Add current number to sum maxProfit = [Link](maxProfit, price - minPrice);
maxSum = [Link](maxSum, currentSum); // // potential profit
Update max if needed }}
if (currentSum < 0) { return maxProfit;
currentSum = 0; // Reset if sum is negative }}
}} Rearrange the array in alternating positive and
return maxSum; negative items
}}
KADANES class Solution {
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) {
for(int i=0;i<[Link];i++){ [Link](num); // Add all elements to the HashSet
if(nums[i]>0){ }
result[positive ]=nums[i];
positive=positive+2; int longestStreak = 0;
}
else{
result[negative]=nums[i]; for (int num : set) {
negative=negative+2; // Check if it's the start of a sequence
}} if (![Link](num - 1)) {
return result; int currentNum = num;
}} int currentStreak = 1;

Leaders in array
// Count consecutive elements
import [Link].*; while ([Link](currentNum + 1))
{
currentNum++;
public class Solution {
currentStreak++;
public List<Integer> findLeaders(int[] arr) {
}
List<Integer> leaders = new ArrayList<>();
int n = [Link];
longestStreak = [Link](longestStreak,
currentStreak);
int maxFromRight = arr[n - 1];
}
[Link](maxFromRight); // Rightmost
return longestStreak;
element is always a leader
}}
SET MATRIX ZEROES
// Traverse from second last to the beginning
for (int i = n - 2; i >= 0; i--) { class Solution {
if (arr[i] > maxFromRight) { public void setZeroes(int[][] matrix) {
maxFromRight = arr[i]; int rows = [Link];
[Link](maxFromRight); int cols = matrix[0].length;
}}
// Leaders collected in reverse order,
// First pass: mark rows and columns
reverse 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] == 0) {
}}
markRow(matrix, i);
markCol(matrix, j);
}}}
Longest Consecutive Sequence // Second pass: convert all -1 to 0
for (int i = 0; i < rows; i++) {
Input: nums = [100,4,200,1,3,2]
for (int j = 0; j < cols; j++) {
Output: 4
Explanation: The longest consecutive elements sequence is [1, if (matrix[i][j] == -1) {
2, 3, 4]. Therefore its length is 4. matrix[i][j] = 0;
}}}}
Optimised Solution private void markRow(int[][] matrix, int row) {
for (int j = 0; j < matrix[0].length; j++) {
import [Link]; if (matrix[row][j] != 0) {
matrix[row][j] = -1; // mark
}}} 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++) { ROTATE IMAGE
for (int j = 0; j < cols; j++) {
if (matrix[i][j] == 0) { class Solution {
row[i] = 1; public void rotate(int[][] matrix) {
col[j] = 1; int n = [Link];
}}} int[][] temp = new int[n][n]; // extra matrix
// Step 2: Set matrix cells to 0 if their // Copy elements to temp in rotated position
row or column is marked for (int i = 0; i < n; i++) {
for (int i = 0; i < rows; i++) { for (int j = 0; j < n; j++) {
for (int j = 0; j < cols; j++) { temp[j][n - 1 - i] = matrix[i][j];
if (row[i] == 1 || col[j] == 1) { }}
matrix[i][j] = 0; // Copy back to original matrix
}}}} for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = temp[i][j];
Optimised solution }}}}
Optimised solution
class Solution {
public void setZeroes(int[][] matrix) { class Solution {
int rows = [Link]; public void rotate(int[][] matrix) {
int cols = matrix[0].length; int n = [Link];
int col0 = 1; // Track whether the first // Step 1: Transpose the matrix
column needs to be zeroed for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// Swap matrix[i][j] with matrix[j][i]
// Step 1: Mark the first row, column, and
int temp = matrix[i][j];
col0 based on zero positions
matrix[i][j] = matrix[j][i];
for (int i = 0; i < rows; i++) {
matrix[j][i] = temp;
if (matrix[i][0] == 0) col0 = 0; // first
}}
column marker
// Step 2: Reverse each row
for (int j = 1; j < cols; j++) {
for (int i = 0; i < n; i++) {
if (matrix[i][j] == 0) {
int left = 0, right = n - 1;
matrix[i][0] = 0; // mark row
while (left < right) {
matrix[0][j] = 0; // mark column
// Swap matrix[i][left] and matrix[i][right]
}}}
int temp = matrix[i][left];
// Step 2: Use the markers to update the
matrix[i][left] = matrix[i][right];
cells (except first row and col)
matrix[i][right] = temp; }
left++; [Link]();
right--; }
}}}}
HARD PROBLEMS
public class Solution {

PASCAL TRIANGLE
// Helper function to calculate nCr
[Link] the value of element by number of row public int nCr(int n, int r) {
long res = 1;
and column
public class Pascal { for (int i = 0; i < r; i++) {
res = res * (n - i);
res = res / (i + 1);
// Function to calculate nCr efficiently
}
public static long nCr(int n, int r) {
return (int) res;
long res = 1;
}
// Main function to generate Pascal's Triangle
// Since C(n, r) = C(n, n - r) public List<List<Integer>> generate(int numRows)
if (r > n - r) {
r = n - r; List<List<Integer>> ans = new ArrayList<>();

for (int i = 0; i < r; i++) { for (int row = 1; row <= numRows; row++) {
res = res * (n - i); List<Integer> tempList = new ArrayList<>();
res = res / (i + 1); for (int col = 1; col <= row; col++) {
} [Link](nCr(row - 1, col - 1));
return res; }
} [Link](tempList);
}
public static int pascalTriangle(int r, int c) {
int element = (int) nCr(r - 1, c - 1);
return ans;
return element;
}
}
}
R=5,C=3 5*4*3/3*2*1 =6 Optimal Solution
[Link] elements in row import [Link].*;

public class Main {


public static long nCr(int n, int r) { public class Solution {
long res = 1; public List<List<Integer>> generate(int numRows)
// calculating nCr: {
for (int i = 0; i < r; i++) { List<List<Integer>> triangle = new
res = res * (n - i); ArrayList<>();
res = res / (i + 1);
} for (int row = 0; row < numRows; row++) {
return res; List<Integer> currentRow = new
} ArrayList<>();
public static void pascalTriangle(int n) { [Link](1); // first element is always 1
// printing the entire row n: // Fill the middle elements based on previous row
for (int c = 1; c <= n; c++) { for (int col = 1; col < row; col++) {
[Link](nCr(n - 1, c - 1) + " int val = [Link](row -
"); 1).get(col - 1) + [Link](row - 1).get(col);
[Link](val); int n = [Link];
} List<Integer> result = new ArrayList<>();

if (row > 0) { for (int i = 0; i < n; i++) {


[Link](1); // last element // Skip if nums[i] is already in result
is also 1 if row > 0 if ([Link]() == 0 ||
} [Link](0) != nums[i]) {
if ([Link]() == 2 &&
[Link](currentRow); [Link](1) == nums[i]) continue;
}
int count = 0;
return triangle; for (int j = 0; j < n; j++) {
} if (nums[j] == nums[i]) {
} count++;
}
}
Majority Elements(N/3 times)
if (count > n / 3) {
class Solution { [Link](nums[i]);
public List<Integer> majorityElement(int[] nums) }
{ }
int n = [Link];
List<Integer> result = new ArrayList<>();
for (int i = 0; i < n; i++) { if ([Link]() == 2) break;
// Skip if nums[i] is already in result }
if ([Link]() == 0 ||
[Link](0) != nums[i]) { return result;
if ([Link]() == 2 && }
[Link](1) == nums[i]) continue; }

int count = 0;
for (int j = 0; j < n; j++) {
if (nums[j] == nums[i]) { Optimal Solution
count++;
} class Solution {
} public List<Integer> majorityElement(int[] nums)
{
if (count > n / 3) { int n = [Link];
[Link](nums[i]); int count1 = 0, count2 = 0;
} int candidate1 = Integer.MIN_VALUE,
} candidate2 = Integer.MIN_VALUE;

if ([Link]() == 2) break; // 1st pass: Find potential candidates


} for (int num : nums) {
if (count1 == 0 && num != candidate2) {
count1 = 1;
return result;
candidate1 = num;
}
} else if (count2 == 0 && num !=
}
candidate1) {
import [Link].*;
count2 = 1;
class Solution {
candidate2 = num;
public List<Integer> majorityElement(int[] nums)
} else if (num == candidate1) {
{
count1++; Set<List<Integer>> set = new HashSet<>();
} else if (num == candidate2) {
count2++; // Try every triplet combination
} else { for (int i = 0; i < n; i++) {
count1--; for (int j = i + 1; j < n; j++) {
count2--; for (int k = j + 1; k < n; k++) {
} if (nums[i] + nums[j] + nums[k] == 0) {
} List<Integer> triplet =
[Link](nums[i], nums[j], nums[k]);
// 2nd pass: Verify actual counts [Link](triplet);
count1 = 0; // Sort to avoid duplicate permutations
count2 = 0; [Link](triplet);
for (int num : nums) { // Set automatically handles duplicates
if (num == candidate1) count1++; }
else if (num == candidate2) count2++; }
} }
}
List<Integer> result = new ArrayList<>(); return new ArrayList<>(set);
int threshold = n / 3; }
}

if (count1 > threshold)


[Link](candidate1);
class Solution {
if (count2 > threshold)
public List<List<Integer>> threeSum(int[] nums)
[Link](candidate2);
{
int n = [Link];
return result; Set<List<Integer>> st = new HashSet<>();
} for (int i = 0; i < n; i++) {
} Set<Integer> hashset = new HashSet<>();
for (int j = i + 1; j < n; j++) {
int third = -(nums[i] + nums[j]);
if ([Link](third)) {
List<Integer> temp =
[Link](nums[i], nums[j], third);
[Link](temp);
[Link](temp);
}
[Link](nums[j]);
}
}

return new ArrayList<>(st);


}
}
Optimal Solution
import [Link].*;
3 SUM
class Solution { class Solution {
public List<List<Integer>> threeSum(int[] nums) public List<List<Integer>> threeSum(int[] nums)
{ {
int n = [Link]; List<List<Integer>> ans = new ArrayList<>();
[Link](nums); int maxi = 0;
int n = [Link]; int sum = 0;

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


// Skip duplicates for the first number
if (i > 0 && nums[i] == nums[i - 1]) sum += A[i];
continue; if(sum == 0) {
maxi = i + 1;
int j = i + 1; }
int k = n - 1; else {
if([Link](sum) != null) {
while (j < k) {
int sum = nums[i] + nums[j] + maxi = [Link](maxi, i -
nums[k]; [Link](sum));
}
if (sum < 0) { else {
j++; [Link](sum, i);
} else if (sum > 0) { }
k--; }
} else { }
return maxi;
[Link]([Link](nums[i], nums[j], nums[k])); }
j++;
k--;

//Skip duplicates for second and third numbers


while (j < k && nums[j] == nums[j - 1]) j++; class Solution {
while (j < k && nums[k] == nums[k + 1]) k--; public int maxLengthZeroSumSubarray(int[] nums)
} {
} int max = 0;
} int n = [Link];
for (int i = 0; i < n; ++i) {
int sum = 0;
return ans;
for (int j = i; j < n; ++j) {
}
sum += nums[j];
}
if (sum == 0) {
max = [Link](max, j - i + 1);
}
}
}
return max;
}
}
Largest Subarray with 0 Sum

Optimal Solution

int maxLen(int A[], int n)


{
// Your code here
HashMap<Integer, Integer> mpp = new
HashMap<Integer, Integer>();
Count number of subarrays with given xor K public class tUf {

class Solution {
public static int subarraysWithXorK(int []a, int
public int subarraysWithXorK(int[] nums, int k)
k) {
{
int n = [Link]; //size of the given array.
int count = 0;
int xr = 0;
int n = [Link];
Map<Integer, Integer> mpp = new HashMap<>();
//declaring the map.
for (int i = 0; i < n; i++) { [Link](xr, 1); //setting the value of 0.
for (int j = i; j < n; j++) { int cnt = 0;
int xor = 0;
for (int l = i; l <= j; l++) {
for (int i = 0; i < n; i++) {
xor ^= nums[l];
// prefix XOR till index i:
}
xr = xr ^ a[i];
if (xor == k) count++;
}
} //By formula: x = xr^k:
int x = xr ^ k;

return count;
} // add the occurrence of xr^k
} // to the count:
if ([Link](x)) {
cnt += [Link](x);
}

public class tUf {


// Insert the prefix xor till index i
// into the map:
public static int subarraysWithXorK(int []a, int
if ([Link](xr)) {
k) {
[Link](xr, [Link](xr) + 1);
int n = [Link]; //size of the given array.
} else {
int cnt = 0;
[Link](xr, 1);
}
// Step 1: Generating subarrays: }
for (int i = 0; i < n; i++) { return cnt;
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;
}

You might also like