Monday, January 25, 2021

Check If All 1's Are at Least Length K Places Away in an Array

Problem: Given an array nums of 0s and 1s and an integer k, return True if all 1's are at least k places away from each other, otherwise return False.

Example:

Input: nums = [1,0,0,0,1,0,0,1,0,0], k = 2
Output: true
Explanation: Each of the 1s are at least 2 places away from each other.
Input: nums = [1,0,0,1,0,1], k = 2
Output: false
Explanation: The second 1 and third 1 are only one apart from each other.


Approach: Nothing to explain as its an easy problem to solve. You can understand the approach by just looking at the implementation.


Implementation in C#:

        public static bool KLengthApart(int[] nums, int k)

        {

            if (nums?.Length <= 1)

            {

                return true;

            }

            for (int i = 0; i < nums.Length;)

            {

                if (nums[i] == 1)

                {

                    ++i;

                    for (int j = 0; j < k && i < nums.Length; ++j)

                    {

                        if (nums[i] == 1)

                        {

                            return false;

                        }

                        ++i;

                    }

                }

                else

                {

                    ++i;


                }

            }

            return true;

        }


Complexity: O(n)

No comments:

Post a Comment