Java Program to Find the Largest Subarray with Equal Number of 0s and 1s
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This is the Java Program to Find the Largest sub-Array consisting of Equal Number of 0’s and 1’s.
Given an array, find out the longest subarray consisting of the equal number of zeroes and ones.
Example:
ArrayOne = [1, 2, 0, 5, 6, 0, 1, 0]
Output
1 2 0 5 6 0 1
Maintain two variables start and end to store the starting and ending index of the subarray and initialize them to -1. Also, create a boolean variable flag mark it to be true. Iterate through the array, and check if the element is 0 or 1 if it is one and the flag is true set the flag to false, otherwise set the flag to true and update the variables starting and ending indexes.
Here is the source code of the Java Program to Find the Largest sub-Array consisting of Equal Number of 0’s and 1’s. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.
// Java Program to Find the Largest sub-Array
// Consisting of Equal Number of 0's and 1's
// Function to find out the largest subarray having equal zeroes and ones.
}
}
}
}
}
}
}
// Function to read the input and to display the subarray
}
}
}
}
}
}
}
1. In function largestSubarray(), the variables start and end are initialized to -1 and flag is set to true.
2. The loop for(i=0; i<array.length; i++) is used to iterate through the array.
3. The condition if(array[i] == 0 || array[i] == 1) checks for zero and one.
4. The nested condition if(start == -1) checks if the current element is the first element of the subarray.
5. The nested condition else if(flag) checks if the number of zeroes and ones were previously equal.
6. The else part sets the end variable to point to the last entry of the subarray.
Time Complexity: O(n) where n is the number of elements in the array.