Skip to content

malakmohamed172/Longest-Balanced-Subarray

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🔢 Longest Balanced Binary Subarray Finder

A Java Swing desktop app that finds the longest contiguous subarray with an equal number of 0s and 1s.

Java Platform License Status

Longest Balanced Binary Subarray Finder main result

📖 Overview

Longest Balanced Binary Subarray Finder is a lightweight Java Swing desktop application that solves a classic array problem: given a binary array (only 0s and 1s), find the length of the longest contiguous subarray containing an equal number of 0s and 1s.

The app runs two implementations side by side so results can be cross-checked instantly:

🔁 Non-recursive ♻️ Recursive
Iterative prefix-sum approach Recursive prefix-sum approach

✨ Features

  • 🖥️ Simple, intuitive Java Swing graphical interface
  • ⌨️ Space-separated binary array input
  • ⚖️ Side-by-side comparison of recursive vs. non-recursive results
  • ⚠️ Clear, descriptive validation messages for invalid input
  • 🧾 Clean output panel showing the parsed array and final result

🧠 Algorithm Idea

The core trick: treat each 0 as -1 and each 1 as +1, then track running prefix sums.

When the same prefix sum appears twice, the elements between those two indices must contain an equal number of 0s and 1s. The maximum distance between two indices sharing a prefix sum gives the longest balanced subarray length.


⏱️ Complexity

Approach Time Complexity Space Complexity
Non-recursive O(n) O(n)
Recursive O(n) O(n)

📁 Project Structure

.
├── src/
│   ├── LongestBalancedSubarray.java
│   └── LongestBalancedSubarrayGUI.java
├── screenshots/
└── README.md

🚀 Run Locally

1. Compile the project

javac src/*.java

2. Run the GUI

java -cp src LongestBalancedSubarrayGUI

🧪 Example Inputs

0 1
0 1 0
0 0 1 0 1 1 0
0 0 0 0

🖼️ Screenshots

✅ Valid Results

Balanced input with result 2
Balanced input → result 2
Short binary input with result 2
Short array → result 2
Long binary input with result 6
Long array → result 6
All zeroes input with result 0
All zeroes → result 0

🚫 Input Validation

Input spacing error dialog
Spacing error
Invalid format error dialog
Invalid format
Only zero and one validation error dialog
Only 0/1 allowed
Letter input format error dialog
Letter input error

👤 Contributor

Created with ❤️ by malakmohamed217


If you found this project useful, consider giving it a ⭐!

About

Java Swing desktop application that finds the length of the longest balanced binary subarray containing an equal number of 0s and 1s, using both recursive and non-recursive prefix-sum approaches with input validation and result comparison.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages