Skip to content

Python Exercises

Arrays

Second largest

second_largest.py
# Given an array of positive integers arr[], return the second largest element from the array. 
# If the second largest element doesn't exist then return -1.
# Note: The second largest element should not be equal to the largest element.

class SecondLargest:
    def getSecondLargest(self, arr):
        n = len(arr)
        largest = -1
        secondLargest = -1

        for i in range(n):
            if arr[i] > largest:
                largest = arr[i]

        for i in range(n):
            if arr[i] > secondLargest and arr[i] != largest:
                secondLargest = arr[i]

        return secondLargest

if __name__=="__main__":
    arr = [12, 35, 1, 10, 34, 1]
    solution = SecondLargest()

Move zeros to end

push_zeros_end.py
# Given an array arr[]. Push all the zeros of the given array to the right end of the array while maintaining the order of non-zero elements. 
# Do the mentioned change in the array in place.

class ZerosEnd:
    def pushZerosToEnd(self,arr):
        count = 0

        for i in range(len(arr)):
            if arr[i] != 0:
                arr[count] = arr[i]
                count += 1

        for i in range(count, len(arr)):
            arr[i] = 0

        return arr

if __name__=='__main__':
    arr = [1, 2, 0, 4, 3, 0, 5, 0]
    solution = ZerosEnd()

Reverse array

reverse_array.py
# You are given an array of integers arr[]. 
# Your task is to reverse the given array.

class ReverseArray:
    def reverseArray(self, arr):
        left = 0
        right = len(arr) - 1

        while left < right:
            arr[left], arr[right] = arr[right], arr[left]
            left += 1
            right -= 1

if __name__=='__main__':
    arr = [1, 4, 3, 2, 6, 5]
    solution = ReverseArray()

Rotate array

# Given an array arr[]. Rotate the array to the left (counter-clockwise direction) by d steps, where d is a positive integer. 
# Do the mentioned change in the array in place.
# Note: Consider the array as circular.

class Rotate: 
    def rotateArr(self, arr, d):
        n = len(arr)
        d %= n
        temp = [0] * n

        for i in range(n - d):
            temp[i] = arr[d + i]

        for i in range(d):
            temp[n - d + i] = arr[i]

        for i in range(n):
            arr[i] = temp[i]

if __name__ == "__main__":
    arr = [1, 2, 3, 4, 5, 6]
    d = 2
    solution = Rotate()