Track5_Arrays Flashcards

1
Q

Write a function that computes the second largest element of an array.

A

Following solution finds the second largest element in a single pass.

int findSecLargest(int[] arr, int n){
largest_index = 0
second_largest = -1

      for(i=1;i<n;i++){
            if(arr[i] > arr[largest_index]){
                     second_largest = largest_index
                     largest_index = i
             }else if(arr[i]!=arr[largest_index]){
                    if(second_largest==-1   OR arr[second_largest]<arr[i])
                          second_largest = i
             }
       }
       return second_largest; }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Write a function that rotates an array left by ā€˜dā€™ elements.

A

rotate_left(arr, Len, d):
reverse (arr, 0, d-1)
reverse(arr, d, len-1)
reverse (arr, 0, len-1)

Time : Theta(n)
Aux space : Theta(1)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Move the zeros in an array to the end, while maintaining the order of all other non-zero elements.
Eg. 1,2, 0, 1, 5, 0, 3
Output: 1, 2, 1, 5, 3, 0, 0

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Remove the duplicate elements in a sorted array. And return the number of elements remaining.
Eg : 1, 1, 2, 3, 3, 3, 5, 9
Out : 1, 2, 3, 5, 9, 3, 5, 9 and returns 5.

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly