Similar Problems

Similar Problems not available

Longest Nice Subarray - Leetcode Solution

Companies:

LeetCode:  Longest Nice Subarray Leetcode Solution

Difficulty: Medium

Topics: sliding-window bit-manipulation array  

Problem Description:

Given an array of integers nums, find the longest subarray which is nice.

A subarray is nice if there are no repeated elements and if every element in the subarray is either odd or even.

Return the length of the longest nice subarray of nums. If there is no nice subarray, return 0.

Example 1:

Input: nums = [1,2,3,2,1] Output: 3 Explanation: The longest nice subarray is [1,2,3].

Example 2:

Input: nums = [2,2,2,1,2,1,1,1,2,3,4,5,5,6,6] Output: 6 Explanation: The longest nice subarray is [1,2,1,1,1,2].

Solution:

The solution to this problem can be done in O(n) time complexity. We can traverse the array from left to right and maintain two counters, one for odd elements and another for even elements.

Let's take an example to understand the approach:

nums = [2,3,2,1,1,2,3,4]

Odd counter = 0, Even counter = 0, max_length = 0, last_seen = {}

i=0: nums[i] = 2, Even counter += 1 last_seen[2] = 0

i=1: nums[i] = 3, Odd counter += 1 last_seen[3] = 1

i=2: nums[i] = 2, Even counter += 1 last_seen[2] = 2

i=3: nums[i] = 1, Odd counter += 1 last_seen[1] = 3

i=4: nums[i] = 1, Odd counter += 1 We have repeated element, so reset odd and even counters, start from last_seen[1]+1 and clear last_seen. last_seen = {}, Odd counter = 0, Even counter = 0

i=5: nums[i] = 2, Even counter += 1 last_seen[2] = 5

i=6: nums[i] = 3, Odd counter += 1 last_seen[3] = 6

i=7: nums[i] = 4, Even counter += 1 last_seen[4] = 7

The final max_length is 4.

Code:

Below is the complete code to solve the problem in Python:

def longestNiceSubarray(nums: List[int]) -> int: n = len(nums) odd_count = 0 even_count = 0 max_length = 0 last_seen = {} for i in range(n): if nums[i] % 2 == 0: even_count += 1 else: odd_count += 1 if odd_count == even_count: max_length = max(max_length, odd_count + even_count) elif (odd_count - even_count) in last_seen: max_length = max(max_length, i - last_seen[(odd_count - even_count)]) else: last_seen[(odd_count - even_count)] = i

return max_length

Time Complexity:

The time complexity of the solution is O(n) as we are iterating over the array only once.

Space Complexity:

The space complexity of the solution is also O(n) as we are storing the frequency of the elements in a dictionary.

Longest Nice Subarray Solution Code

1