Find the largest number smaller than a certain number in a sorted array

Find the largest number smaller than a certain number in a sorted array

Difficulty: Easy

Understanding The Problem

Problem Description

Given an array arr[] of size n, write a program to find the largest element in it.

Example 1:

Input: arr[] = [100, 50, 4]
Output: 100
Explanation: 100 is the largest element in the given array.

Solutions

There are various ways to find the largest element. In each programming language, there is support for finding the max in the library. However, internally they work the same. Below are some discussed ways to do that.

  1. Sorting: Sort the array in ascending order and the last element will be at the last index.
  2. Traverse: Traverse the array while updating the max value.

You may try this problem here.

1. Sorting

To find the largest element from the array, a simple way is to arrange the elements in ascending order. After sorting, the first element will represent the smallest element, the next element will be the second smallest, and going on, the last element will be the largest element of the array.

Solution Steps

  • Sort the array.
  • Return the element at the last index of the array.

Pseudo Code

int largestElement(int[] arr, int size) {
    // sort the array in ascending order
    arr.sort()
    largest_element = arr[size-1]
    return largest_element
}

Complexity Analysis

Time Complexity: O(n log n)

Space Complexity: O(1)

Critical Ideas To Think

  • Why did we return the last element?
  • If we would have sorted the array in descending order, then which element we should have returned?
  • Sorting the array arranges each and every element and that will help us to find the largest, 2nd largest, 3rd largest elements and so on in constant time. But is it okay to do that much computation here when we just have to find the largest element?

2. Traverse

Take a max variable and initialize it with the first element of the array. Now start iterating over the array and whenever a larger element encountered then update the max variable otherwise, move forward.

Solution Steps

  1. Create a max variable and initialize it with arr[0]
  2. Iterate from the first idx to the last idx of the array:
  • If arr[idx] > max then update max with arr[idx]

3. Return max

Pseudo Code

int largestElement(int[] arr, int size) {
    int max = arr[0]
    for(int i = 1 to i < size) {
        if(max < arr[i]) {
            max = arr[i]
        }
    }
    return max
}

Complexity Analysis

Time Complexity: O(n)

Space Complexity: O(1)

Critical Ideas To Think

  • Why did we initialize max with arr[0]?
  • What if we initialize max with INT_MIN and start the loop from the 0th index. Will that approach would have worked?
  • What changes do we have to do, when we have to find the 2nd largest element?

Comparison of Solutions

Find the largest number smaller than a certain number in a sorted array

Suggested Problems To Solve

  • Find the smallest element of the array
  • Find the 2nd largest element of the array
  • Find the Kth largest element of the array

Please comment down below if you have a better insight in the above approach.

Happy Coding, Enjoy Algorithms!

Given a sorted integer array, find the floor and ceil of a given number in it. The floor and ceil map the given number to the largest previous or the smallest following integer in the array.

More precisely, for a number x, floor(x) is the largest integer in the array less than or equal to x, and ceil(x) is the smallest integer in the array greater than or equal to x. If the floor or ceil doesn’t exist, consider it to be -1. For example,

Input:

  nums[] = [1, 4, 6, 8, 9]
Number: 0 to 10

  Output:

  Number 0 —> ceil is 1, floor is -1
Number 1 —> ceil is 1, floor is 1
Number 2 —> ceil is 4, floor is 1
Number 3 —> ceil is 4, floor is 1
Number 4 —> ceil is 4, floor is 4
Number 5 —> ceil is 6, floor is 4
Number 6 —> ceil is 6, floor is 6
Number 7 —> ceil is 8, floor is 6
Number 8 —> ceil is 8, floor is 8
Number 9 —> ceil is 9, floor is 9
Number 10 —> ceil is -1, floor is 9

Practice this problem

A simple solution would be to run a linear search on the array and find the largest integer in the array less than or equal to x and the smallest integer in the array greater than or equal to x. That would be the floor and ceil of the number x, respectively. The problem with this approach is that its worst-case time complexity is O(n), where n is the size of the input.

 
We can easily solve this problem in O(log(n)) time by modifying the binary search algorithm. The basic idea remains the same. We find the middle element and move to the left or right subarray based on comparison result with the given number. Following is the complete algorithm:

findCeil(nums[low, high], x)

Initialize ceil to -1 and iterate till our search space is exhausted.

  • If x is equal to the middle element, it is the ceil.
  • If x is less than the middle element, the ceil exists in subarray nums[low…mid]; update ceil to the middle value and reduce our search space to the left subarray nums[low…mid-1].
  • If x is more than the middle element, the ceil exists in the right subarray nums[mid+1…high].

 
findFloor(nums[low, high], x)

Initialize floor to -1 and iterate till our search space is exhausted.

  • If x is equal to the middle element, it is the floor.
  • If x is less than the middle element, the floor exists in the left subarray nums[low…mid-1].
  • If x is more than the middle element, the floor exists in subarray nums[mid…high]; update floor to the middle element and reduce our search space to the right subarray nums[mid+1…high].

The algorithm can be implemented as follows in C, Java, and Python:

C


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

#include

// Function to find the ceil of `x` in a sorted array nums[0…n-1]

// i.e., the smallest integer greater than or equal to `x`

intgetCeil(int nums[],intn,int x)

{

    // search space is nums[low…high]

    intlow =0,high=n- 1,mid;

    // initialize ceil to -1

    int ceil=-1;

    // loop till the search space is exhausted

    while(low<=high)

    {

        // find the mid-value in the search space

        mid=(low+ high)/2;

        // if `x` is equal to the middle element, it is the ceil

        if(nums[mid]==x) {

            returnnums[mid];

        }

        // if `x` is less than the middle element, the ceil exists in the

        // subarray nums[low…mid]; update ceil to the middle element

        // and reduce our search space to the left subarray nums[low…mid-1]

        elseif(x< nums[mid])

        {

            ceil=nums[mid];

            high=mid-1;

        }

        // if `x` is more than the middle element, the ceil exists in the

        // right subarray nums[mid+1…high]

        else{

            low=mid+1;

        }

    }

    returnceil;

}

// Function to find the floor of `x` in a sorted array nums[0…n-1],

// i.e., the largest integer less than or equal to `x`

intgetFloor(int nums[],intn,int x)

{

    intlow= 0,high=n- 1,mid;

    // initialize floor to -1

    int floor=-1;

    // loop till the search space is exhausted

    while(low<=high)

    {

        // find the mid-value in the search space

        mid=(low+ high)/2;

        // if `x` is equal to the middle element, it is the floor

        if(nums[mid]==x) {

            returnnums[mid];

        }

        // if `x` is less than the middle element, the floor exists in the left

        // subarray nums[low…mid-1]

        else if(x<nums[mid]){

            high=mid- 1;

        }

        // if `x` is more than the middle element, the floor exists in the

        // subarray nums[mid…high]; update floor to the middle element

        // and reduce our search space to the right subarray nums[mid+1…high]

        else{

            floor=nums[mid];

            low=mid+1;

        }

    }

    returnfloor;

}

int main(void)

{

    intnums[] ={1,4,6, 8,9};

    intn =sizeof(nums)/ sizeof(nums[0]);

    for (inti=0;i<=10;i++)

    {

        printf("Number %d —> ",i);

        printf("ceil is %d, ",getCeil(nums,n, i));

        printf("floor is %d\n",getFloor(nums,n,i));

    }

    return0;

}

Download  Run Code

Java


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

classMain

{

    // Function to find the ceil of `x` in a sorted array nums[],

    // i.e., the smallest integer greater than or equal to `x`

    publicstaticintgetCeil(int[]nums,intx)

    {

        // search space is nums[left…right]

        intleft=0,right =nums.length-1;

        // initialize ceil to -1

        intceil=-1;

        // loop till the search space is exhausted

        while(left<=right)

        {

            // find the mid-value in the search space

            int mid=(left+right) /2;

            // if `x` is equal to the middle element, it is the ceil

            if(nums[mid]==x) {

                returnnums[mid];

            }

            // if `x` is less than the middle element, the ceil exists in the

            // subarray nums[left…mid]; update ceil to the middle element

            // and reduce our search space to the left subarray nums[left…mid-1]

            elseif(x<nums[mid])

            {

                ceil=nums[mid];

                right=mid-1;

            }

            // if `x` is more than the middle element, the ceil exists in the

            // right subarray nums[mid+1…right]

            else{

                left=mid +1;

            }

        }

        returnceil;

    }

    // Function to find the floor of `x` in a sorted array nums[],

    // i.e., the largest integer less than or equal to `x`

    publicstaticint getFloor(int[]nums,intx)

    {

        intleft=0,right=nums.length-1;

        // initialize floor to -1

        intfloor= -1;

        // loop till the search space is exhausted

        while (left<=right)

        {

            // find the mid-value in the search space

            intmid=(left +right)/2;

            // if `x` is equal to the middle element, it is the floor

            if(nums[mid] ==x){

                return nums[mid];

            }

            // if `x` is less than the middle element, the floor exists in the left

            // subarray nums[left…mid-1]

            elseif (x<nums[mid]){

                right=mid-1;

            }

            // if `x` is more than the middle element, the floor exists in the

            // subarray nums[mid…right]; update floor to the middle element

            // and reduce our search space to the right subarray nums[mid+1…right]

            else{

                floor=nums[mid];

                left=mid+1;

            }

        }

        returnfloor;

    }

    publicstaticvoid main(String[]args)

    {

        int[]nums={1, 4,6,8,9};

        for(inti=0;i<=10;i++){

            System.out.println("Number "+ i+" —> ceil is "+ getCeil(nums,i)

                    +", floor is "+getFloor(nums,i));

        }

    }

}

Download  Run Code

Python


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

# Function to find the ceil of `x` in a sorted list `nums`,

# i.e., the smallest integer greater than or equal to `x`

defgetCeil(nums, x):

    # search space is nums[left…right]

    (left, right)=(0,len(nums)-1)

    # initialize ceil to -1

    ceil= -1

    # loop till the search space is exhausted

    whileleft<= right:

        # find the mid-value in the search space

        mid= (left+right)//2

        # if `x` is equal to the middle element, it is the ceil

        ifnums[mid]== x:

            returnnums[mid]

        # if `x` is less than the middle element, the ceil exists in the

        # sublist nums[left…mid]; update ceil to the middle element

        # and reduce our search space to the left sublist nums[left…mid-1]

        elifx<nums[mid]:

            ceil=nums[mid]

            right =mid-1

        # if `x` is more than the middle element, the ceil exists in the

        # right sublist nums[mid+1…right]

        else:

            left= mid+1

    returnceil

# Function to find the floor of `x` in a sorted list `nums`,

# i.e., the largest integer less than or equal to `x`

defgetFloor(nums,x):

    (left,right)=(0, len(nums)-1)

    # initialize floor to -1

    floor=-1

    # loop till the search space is exhausted

    while left<=right:

        # find the mid-value in the search space

        mid=(left+right) //2

        # if `x` is equal to the middle element, it is the floor

        if nums[mid]==x:

            returnnums[mid]

        # if `x` is less than the middle element, the floor exists in the left

        # sublist nums[left…mid-1]

        elifx< nums[mid]:

            right= mid-1

        # if `x` is more than the middle element, the floor exists in the

        # sublist nums[mid…right]; update floor to the middle element

        # and reduce our search space to the right sublist nums[mid+1…right]

        else:

            floor=nums[mid]

            left =mid+1

    returnfloor

if__name__=='__main__':

    nums =[1,4,6, 8,9]

    foriin range(max(nums)+2):

        print(f'Number {i} —> ceil is {getCeil(nums, i)},floor is {getFloor(nums, i)}')

Download  Run Code

Output:

  Number 0 —> ceil is 1, floor is -1
Number 1 —> ceil is 1, floor is 1
Number 2 —> ceil is 4, floor is 1
Number 3 —> ceil is 4, floor is 1
Number 4 —> ceil is 4, floor is 4
Number 5 —> ceil is 6, floor is 4
Number 6 —> ceil is 6, floor is 6
Number 7 —> ceil is 8, floor is 6
Number 8 —> ceil is 8, floor is 8
Number 9 —> ceil is 9, floor is 9
Number 10 —> ceil is -1, floor is 9

The time complexity of the above solution is O(log(n)) and doesn’t require any extra space.

 
Exercise: Write a recursive solution to find the floor and ceil of a number.

Thanks for reading.

Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Like us? Refer us to your friends and help us grow. Happy coding :)


How do you find the number of elements greater smaller than an element in an array?

The simplest trick is sort the array first and count the number of elements in the array. So for example if you have 10 elements then your first element is less than 9 and likewise the second element is smaller than 8 and so on.

How do you find the largest and smallest number in an array?

Algorithm to find the smallest and largest numbers in an array.
Input the array elements..
Initialize small = large = arr[0].
Repeat from i = 2 to n..
if(arr[i] > large).
large = arr[i].
if(arr[i] < small).
small = arr[i].
Print small and large..

How do you find the largest and smallest number in an unsorted array in C?

Logic to find the largest and smallest element in the array.
Create two intermediate variables small and large..
Initialize the small and large variable with arr[0]..
Now traverse the array iteratively and keep track of the smallest and largest element until the end of the array..