3719. Longest Balanced Subarray I
UnknownView on LeetCode
Time: O(n)
Space: O(n)
Problem Overview
Longest Balanced Subarray I (Unknown) asks you to solve a structured algorithmic task. This is a common Array pattern in coding interviews. Find longest subarray where all elements appear equal number of times.
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
Find longest subarray where all elements appear equal number of times.
Related patterns: Array
3719.cs
C#
// Approach: Find longest subarray where all elements appear equal number of times.
// Time: O(n) Space: O(n)
public class Solution
{
public int LongestBalanced(int[] nums)
{
int n = nums.Length;
int ans = 0;
for (int i = 0; i < n; ++i)
{
HashSet<int> vis = new HashSet<int>();
int[] cnt = new int[2];
for (int j = i; j < n; ++j)
{
if (vis.Add(nums[j]))
++cnt[nums[j] & 1];
if (cnt[0] == cnt[1])
ans = Math.Max(ans, j - i + 1);
}
}
return ans;
}
}Was this solution helpful?
Related Problems
- 4. Median of Two Sorted Arrays(Hard)
- 11. Container With Most Water(Medium)
- 15. 3Sum(Medium)
- 16. 3Sum Closest(Medium)
- 26. Remove Duplicates from Sorted Array(Easy)
- 27. Remove Element(Easy)