Рет қаралды 655
Convert Array into Zig Zag
In this class, We discuss Convert Array into Zig Zag
The reader can take the complete competitive coding course. Click Here.
Question:
Given N distinct array elements.
The task is to rearrange the elements in a zig-zag fashion so that the converted array should be in the below form.
arr[0] lt arr[1] gt arr[2] lt arr[3] gt . . . .
Example:
arr[] = [4, 3, 7, 8, 2, 6, 1]
Output: [3, 7, 4, 8, 2, 6, 1]
Time complexity = O(N)
Space complexity = O(1)
Logic:
[4, 3, 7, 8, 2, 6, 1]
Condition:
even position element condition = arr[i] lt arr[i+1]
odd position element condition = arr[i] gt arr[i+1]
Code: less than and greater than symbols changed to lt and gt
class Solution:
def zigZag(self, arr, n):
flag = 1
for i in range(n-1):
if flag == 1:
if arr[i] gt arr[i+1]:
arr[i], arr[i+1] = arr[i+1], arr[i]
else:
if arr[i] lt arr[i+1]:
arr[i], arr[i+1] = arr[i+1], arr[i]
flag = (1 - flag)
print(arr)
n = int(input())
arr=list(map(int,input().strip().split()))
ob = Solution()
ob.zigZag(arr,n)
print(arr)
Link for playlists:
/ @learningmonkey
Link for our website: learningmonkey.in
Follow us on Facebook @ / learningmonkey
Follow us on Instagram @ / learningmonkey1
Follow us on Twitter @ / _learningmonkey
Mail us @ learningmonkey01@gmail.com