A short, fun, and potentially challenging coding problem that I “randomed” on Leetcode
https://leetcode.com/problems/contiguous-array/
Given a binary array, find the maximum length of a contiguous subarray with an equal number of 0 and 1.
Example 1:
Input: [0,1] Output: 2 Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.
Example 2:
Input: [0,1,0] Output: 2 Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.
Note: The length of the given binary array will not exceed 50,000.
Solution:
This solution is superior to 100% other submissions in Kotlin (which are not a lot) in both time and memory space.

The idea of this solution is to give each item an int tag base on its value and its predecessor’s tag (+1 for “1”, -1 for “0”). If a subarray forms a contiguous array, the total sum of all plus and minus from this array must be 0. Therefore, the item preceded the sub-array and the sub’s last item will have the same tag. Use hashmap to find and compare pairs of tags in O(n) time complexity.

class Solution {
    fun findMaxLength(nums: IntArray): Int {
        var n = nums.size
        if (n==0) return 0
        
        var markers = IntArray(n+1)
        //For each slot, +1 if it = 1, -1 if it = 0
        //Array start at 1
        markers[0] = 0
        for (i in 1..n) {
            if (nums[i-1]==1) markers[i] = markers[i-1]+1
            else markers[i] = markers[i-1]-1
            //print(markers[i])
        }
        //println()
        var longestSub = 0
        var hashMap: HashMap<Int,Int> = HashMap()
        for (i in 0..n) {
            if (!hashMap.containsKey(markers[i])) {
                hashMap.put(markers[i], i)
            } else {
                var diff = i-hashMap.get(markers[i])!!
                if (longestSub<diff) longestSub = diff
            }
        }
            
        return longestSub
        
    }
}

m.quan.lam Uncategorized