数据结构--常见数组面试题

常见数组代码面试题

答案:

Find the smallest and second smallest elements in an array

Write an efficient C program to find smallest and second smallest element in an array.

 

Example:


 

Input:  arr[] = {12, 13, 1, 10, 34, 1}
Output: The smallest element is 1 and 
        second Smallest element is 10

Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.

A Simple Solution is to sort the array in increasing order. The first two elements in sorted array would be two smallest elements. Time complexity of this solution is O(n Log n).

A Better Solution is to scan the array twice. In first traversal find the minimum element. Let this element be x. In second traversal, find the smallest element greater than x. Time complexity of this solution is O(n).

The above solution requires two traversals of input array.

An Efficient Solution can find the minimum two elements in one traversal. Below is complete algorithm.

Algorithm:

1) Initialize both first and second smallest as INT_MAX
   first = second = INT_MAX
2) Loop through all the elements.
   a) If the current element is smaller than first, then update first 
       and second. 
   b) Else if the current element is smaller than second then update 
    second

Implementation:

filter_none

edit

play_arrow

brightness_4

<?php

// PHP  program to find smallest and

// second smallest elements

  

function print2Smallest($arr, $arr_size)

{

    $INT_MAX = 2147483647;

      

    /* There should be atleast 

       two elements */

    if ($arr_size < 2)

    {

        echo(" Invalid Input ");

        return;

    }

  

    $first = $second = $INT_MAX;

    for ($i = 0; $i < $arr_size ; $i ++)

    {

          

        /* If current element is

           smaller than first then

           update both first and

           second */

        if ($arr[$i] < $first)

        {

            $second = $first;

            $first = $arr[$i];

        }

  

        /* If arr[i] is in between

           first and second then 

           update second */

        else if ($arr[$i] < $second && 

                 $arr[$i] != $first)

            $second = $arr[$i];

    }

    if ($second == $INT_MAX)

        echo("There is no second smallest element\n");

    else

        echo "The smallest element is ",$first

             ," and second Smallest element is "

                                     , $second;

}

  

// Driver Code

$arr = array(12, 13, 1, 10, 34, 1);

$n = count($arr);

print2Smallest($arr, $n)

  

// This code is contributed by Smitha

?>


Output :

The smallest element is 1 and second Smallest element is 10

The same approach can be used to find the largest and second largest elements in an array.

Non-Repeating Element

Find the first non-repeating element in a given array of integers.

Examples:

Input : -1 2 -1 3 2
Output : 3
Explanation : The first number that does not 
repeat is : 3

Input : 9 4 9 6 7 4
Output : 6

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

A Simple Solution is to use two loops. The outer loop picks elements one by one and inner loop checks if the element is present more than once or not.


 

filter_none

edit

play_arrow

brightness_4

<?php

// Simple PHP program to find first non-

// repeating element.

  

function firstNonRepeating($arr, $n)

{

    for ($i = 0; $i < $n; $i++)

    {

        $j;

        for ($j = 0; $j< $n; $j++)

            if ($i != $j && $arr[$i] == $arr[$j])

                break;

        if ($j == $n)

            return $arr[$i];

    }

    return -1;

}

  

    // Driver code

    $arr = array(9, 4, 9, 6, 7, 4);

    $n = sizeof($arr) ;

    echo firstNonRepeating($arr, $n);

      

// This code is contributed by ajit

?>

Output:

6

Merge two sorted arrays

Given two sorted arrays, the task is to merge them in a sorted manner.

Examples:

Input: arr1[] = { 1, 3, 4, 5}, arr2[] = {2, 4, 6, 8}
Output: arr3[] = {1, 2, 3, 4, 4, 5, 6, 8}

Input: arr1[] = { 5, 8, 9}, arr2[] = {4, 7, 8}
Output: arr3[] = {4, 5, 7, 8, 8, 9}

Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.


 

Method 1 (O(n1 * n2) Time and O(1) Extra Space)

  1. Create an array arr3[] of size n1 + n2.
  2. Copy all n1 elements of arr1[] to arr3[]
  3. Traverse arr2[] and one by one insert elements (like insertion sort) of arr3[] to arr1[]. This step take O(n1 * n2) time.

We have discussed implementation of above method in Merge two sorted arrays with O(1) extra space

Method 2 (O(n1 + n2) Time and O(n1 + n2) Extra Space)
The idea is to use Merge function of Merge sort.

  1. Create an array arr3[] of size n1 + n2.
  2. Simultaneously traverse arr1[] and arr2[].
    • Pick smaller of current elements in arr1[] and arr2[], copy this smaller element to next position in arr3[] and move ahead in arr3[] and the array whose element is picked.
  3. If there are remaining elements in arr1[] or arr2[], copy them also in arr3[].

Below image is a dry run of the above approach:

数据结构--常见数组面试题数据结构--常见数组面试题转存失败重新上传取消数据结构--常见数组面试题

Below is the implementation of the above approach:

filter_none

edit

play_arrow

brightness_4

<?php 

// PHP program to merge

// two sorted arrays

  

// Merge $arr1[0..$n1-1] and 

//       $arr2[0..$n2-1] into

//       $arr3[0..$n1+$n2-1]

function mergeArrays(&$arr1, &$arr2

                      $n1, $n2, &$arr3)

{

    $i = 0;

    $j = 0;

    $k = 0;

  

    // Traverse both array

    while ($i < $n1 && $j < $n2)

    {

        // Check if current element 

        // of first array is smaller 

        // than current element of 

        // second array. If yes, 

        // store first array element 

        // and increment first array

        // index. Otherwise do same

        // with second array

        if ($arr1[$i] < $arr2[$j])

            $arr3[$k++] = $arr1[$i++];

        else

            $arr3[$k++] = $arr2[$j++];

    }

  

    // Store remaining elements 

    // of first array

    while ($i < $n1)

        $arr3[$k++] = $arr1[$i++];

  

    // Store remaining elements

    // of second array

    while ($j < $n2)

        $arr3[$k++] = $arr2[$j++];

}

  

// Driver code

$arr1 = array(1, 3, 5, 7);

$n1 = sizeof($arr1);

  

$arr2 = array(2, 4, 6, 8);

$n2 = sizeof($arr2);

  

$arr3[$n1 + $n2] = array();

mergeArrays($arr1, $arr2, $n1

                   $n2, $arr3);

  

echo "Array after merging \n" ;

for ($i = 0; $i < $n1 + $n2; $i++)

    echo $arr3[$i] . " ";

  

// This code is contributed

// by ChitraNayal

?>


Output:

Array after merging
1 2 3 4 5 6 7 8

 

Rearrange positive and negative numbers in O(n) time and O(1) extra space

An array contains both positive and negative numbers in random order. Rearrange the array elements so that positive and negative numbers are placed alternatively. Number of positive and negative numbers need not be equal. If there are more positive numbers they appear at the end of the array. If there are more negative numbers, they too appear in the end of the array.

For example, if the input array is [-1, 2, -3, 4, 5, 6, -7, 8, 9], then the output should be [9, -7, 8, -3, 5, -1, 2, 4, 6]

Note: The partition process changes relative order of elements. I.e. the order of the appearance of elements is not maintained with this approach. See this for maintaining order of appearance of elements in this problem.


 

The solution is to first separate positive and negative numbers using partition process of QuickSort. In the partition process, consider 0 as value of pivot element so that all negative numbers are placed before positive numbers. Once negative and positive numbers are separated, we start from the first negative number and first positive number, and swap every alternate negative number with next positive number.

Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.

filter_none

edit

play_arrow

brightness_4

<?php

// A PHP program to put positive numbers  

// at even indexes (0, 2, 4,..) and negative 

// numbers at odd indexes (1, 3, 5, ..) 

  

// The main function that rearranges elements 

// of given array. It puts positive elements 

// at even indexes (0, 2, ..) and negative

// numbers at odd indexes (1, 3, ..). 

function rearrange(&$arr, $n

    // The following few lines are similar 

    // to partition process of QuickSort. 

    // The idea is to consider 0 as pivot 

    // and divide the array around it. 

    $i = -1; 

    for ($j = 0; $j < $n; $j++) 

    

        if ($arr[$j] < 0) 

        

            $i++; 

            swap($arr[$i], $arr[$j]); 

        

    

  

    // Now all positive numbers are at end and 

    // negative numbers at the beginning of array. 

    // Initialize indexes for starting point of 

    // positive and negative numbers to be swapped 

    $pos = $i + 1;

    $neg = 0; 

  

    // Increment the negative index by 2 and 

    // positive index by 1, i.e., swap every 

    // alternate negative number with next

    // positive number 

    while ($pos < $n && $neg < $pos && 

                        $arr[$neg] < 0) 

    

        swap($arr[$neg], $arr[$pos]); 

        $pos++; 

        $neg += 2; 

    

  

// A utility function to swap two elements 

function swap(&$a, &$b

    $temp = $a

    $a = $b

    $b = $temp

  

// A utility function to print an array 

function printArray(&$arr, $n

    for ($i = 0; $i < $n; $i++) 

        echo " " . $arr[$i] . " "

  

// Driver Code

$arr = array(-1, 2, -3, 4, 5, 6, -7, 8, 9); 

$n = count($arr); 

rearrange($arr, $n); 

printArray($arr, $n); 

  

// This code is contributed

// by rathbhupendra

?>


Output:

    4   -3    5   -1    6   -7    2    8    9