The Zigzag challenge
Given an array of integers numbers, your task is to check all the triples of its consecutive elements for being a zigzag. More formally, your task is to construct an array of length numbers.length – 2, where the ith element of the output array equals 1 if the triple (numbers[i], numbers[i + 1], numbers[i + 2]) is a zigzag, and 0 otherwise.
Example For numbers = [1, 2, 1, 3, 4], the output should be solution(numbers) = [1, 1, 0]. (numbers[0], numbers[1], numbers[2]) = (1, 2, 1) is a zigzag, because 1 < 2 > 1; (numbers[1], numbers[2] , numbers[3]) = (2, 1, 3) is a zigzag, because 2 > 1 < 3; (numbers[2], numbers[3] , numbers[4]) = (1, 3, 4) is not a zigzag, because 1 < 3 < 4; For numbers = [1, 2, 3, 4], the output should be solution(numbers) = [0, 0]; Since all the elements of numbers are increasing, there are no zigzags. For numbers = [1000000000, 1000000000, 1000000000], the output should be solution(numbers) = [0]. Since all the elements of numbers are the same, there are no zigzags. Input/Output [execution time limit] 4 seconds (js) [input] array.integer numbers An array of integers. Guaranteed constraints: 3 ≤ numbers.length ≤ 100, 1 ≤ numbers[i] ≤ 109. [output] array.integer Return an array, where the ith element equals 1 if the triple (numbers[i], numbers[i + 1], numbers[i + 2]) is a zigzag, and 0 otherwise.“
Illustration?
The zigzag problem is a challenge that appears at CodeSignal and it tests the developer’s skills in using the array smartly,
Zigzag examples
Example 1:
Numbers: [1, 2, 1, 3, 4]
has [1, 2, 1] [2, 1, 3] [1, 3, 4] the output should be [1, 1, 0]
Example 2:
Numbers: [1, 2, 3, 4]
has [1, 2, 3] [2, 3, 4] the output should be [0, 0]
Example 3:
Numbers: [1000000000, 1000000000, 1000000000]
the output should be [0, 0]
Solutions
In the following section, I will illustrate some solutions for this challenge.
Solution 1
int[] ZigzagMethod(int[] numbers) { var size = numbers.Length-2; int[][] numberItems=new int[(int)size][]; for (int i=0;i<numbers.Length-2;i++) { numberItems[i] =new int[]{ numbers[i],numbers[i+1],numbers[i+2] }; } int[] res=new int[numberItems.Length]; int a,b,c; for(int i=0;i< numberItems.Length;i++) { a = numberItems[i][0]; b = numberItems[i][1]; c = numberItems[i][2]; if ((a < b && b > c) || (a > b && b < c)) { res[i] = 1; } else { res[i] = 0; } } return res; }
Conclusion:
The zigzag challenge is one of the most well-known coding challenges in different software coding interviews. In this post, I introduced this challenge with examples and some solutions using c# language You can find sample source codes at github Enjoy…!!!
I can help you to build such as software tools/snippets, you contact me from her