Leetcode Problem 525. Contiguous Array

525. Contiguous Array

Leetcode Solutions

Approach # Using HashMap

  1. Initialize a variable max_length to 0 to store the maximum length of subarray found so far.
  2. Initialize a variable count to 0 to keep track of the relative number of ones and zeros.
  3. Create a HashMap count_map with key as count and value as the index at which this count was first seen.
  4. Initialize count_map with the entry (0, -1) to handle the case when a valid subarray starts from index 0.
  5. Iterate over the array, incrementing count by 1 for every 1 encountered and decrementing by 1 for every 0.
  6. For each index i, check if count is already in count_map.
    • If it is, calculate the length of the subarray from the first occurrence to the current index.
    • Update max_length if this length is greater than the current max_length.
  7. If count is not in count_map, add it with the current index i.
  8. After the loop, return max_length.
UML Thumbnail

Approach # Using Extra Array

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...