File size: 1,583 Bytes
3c88a0f
 
 
 
1
2
3
4
5
{"type": "session", "harness": "opencode", "id": "cp-10032", "name": "LeetCode 0525: Contiguous Array"}
{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}
{"type": "message", "message": {"role": "user", "content": "Problem: Contiguous Array (Difficulty: Medium)\nTags: Array, Hash Table, Prefix Sum\n\nGiven a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1.\n\nExample 1:\nInput: nums = [0,1]\nOutput: 2\nExplanation: [0, 1] is the longest contiguous subarray with an equal number of 0 and 1.\n\nExample 2:\nInput: nums = [0,1,0]\nOutput: 2\nExplanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.\n\nExample 3:\nInput: nums = [0,1,1,1,1,1,0,0,0]\nOutput: 6\nExplanation: [1,1,1,0,0,0] is the longest contiguous subarray with equal number of 0 and 1.\n\nConstraints:\n- 1 <= nums.length <= 10^5\n- nums[i] is either 0 or 1."}}
{"type": "message", "message": {"role": "assistant", "content": "# Time:  O(n)\n# Space: O(n)\n\nclass Solution(object):\n    def findMaxLength(self, nums):\n        \"\"\"\n        :type nums: List[int]\n        :rtype: int\n        \"\"\"\n        result, count = 0, 0\n        lookup = {0: -1}\n        for i, num in enumerate(nums):\n            count += 1 if num == 1 else -1\n            if count in lookup:\n                result = max(result, i - lookup[count])\n            else:\n                lookup[count] = i\n\n        return result\n\n"}}