Created
January 15, 2023 19:43
-
-
Save anushshukla/d310c660c4afebddbbf56400ac73de57 to your computer and use it in GitHub Desktop.
Quizes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Given an array of DISTINCT elements, rearrange the elements of array in zig-zag fashion in O(n) time. | |
| // The converted array should be in form a < b > c < d > e < f. | |
| // Example: | |
| // Input: arr[] = {4, 3, 7, 8, 6, 2, 1} | |
| // Output: arr[] = {3, 7, 4, 8, 2, 6, 1} | |
| // Input: arr[] = {1, 4, 3, 2} | |
| // Output: arr[] = {1, 4, 2, 3} | |
| function zigzag(inputNumbers: number[]) { | |
| const outputNumbers = [...inputNumbers]; | |
| let currIndex = 0; | |
| for (const number of outputNumbers) { | |
| const isEvenIndex = currIndex % 2 === 0; | |
| const nextIndex = currIndex+1; | |
| const nextNumber = outputNumbers[nextIndex]; | |
| if ((isEvenIndex && number > nextNumber) || (!isEvenIndex && number < nextNumber)) { | |
| outputNumbers[currIndex] = nextNumber; | |
| outputNumbers[nextIndex] = number; | |
| } | |
| currIndex++; | |
| } | |
| return outputNumbers; | |
| } | |
| const input = [4, 3, 7, 8, 6, 2, 1]; | |
| const output = zigzag(input); | |
| console.log({ input, output }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment