Floor of every element in same array
Last Updated : 21 Sep, 2023
Given an array of integers, find the closest smaller or same element for every element. If all elements are greater for an element, then print -1. We may assume that the array has at least two elements.
Examples:
Input : arr[] = {10, 5, 11, 10, 20, 12}
Output : 10 -1 10 10 12 11
Note that there are multiple occurrences of 10, so floor of 10 is 10 itself.
Input : arr[] = {6, 11, 7, 8, 20, 12}
Output : -1 8 6 7 12 11
A simple solution is to run two nested loops. We pick an outer element one by one. For every picked element, we traverse remaining array and find closest greater element. Time complexity of this solution is O(n*n)
Algorithm:
- Create a vector to store the result.
- Loop through every element of the array from i = 0 to n-1.
a. Initialize the variable ‘closest’ as INT_MIN.
b. Loop through all elements of the array from j = 0 to n-1
i. If i and j are the same, continue to the next iteration of the loop
ii. If arr[j] is smaller than or equal to arr[i], update the variable closest with maximum of closest and arr[j]
c. If closest is still INT_MIN, push -1 to the result vector else push closest
3. Return the result vector
4. In the main function:
Create an array of integers arr[] of size n
Initialize n as the size of the array arr[]
Call the closestSmallerOrSame function and store the result in a vector called ‘result’
Loop through the result vector and print the elements
Below is the implementation of the approach:
C++
#include <bits/stdc++.h> using namespace std; vector< int > closestSmallerOrSame( int arr[], int n) { vector< int > res; for ( int i = 0; i < n; i++) { int closest = INT_MIN; for ( int j = 0; j < n; j++) { if (i == j) continue ; if (arr[j] <= arr[i]) { closest = max(closest, arr[j]); } } if ( closest == INT_MIN) res.push_back(-1); else res.push_back(closest); } return res; } int main() { int arr[] = { 6, 11, 7, 8, 20, 12 }; int n = sizeof (arr) / sizeof (arr[0]); vector< int > result = closestSmallerOrSame(arr, n); for ( int i = 0; i < result.size(); i++) cout << result[i] << " " ; cout << endl; return 0; } |
Java
import java.util.*; public class GFG { public static List<Integer> closestSmallerOrSame( int [] arr, int n) { List<Integer> res = new ArrayList<>(); for ( int i = 0 ; i < n; i++) { int closest = Integer.MIN_VALUE; for ( int j = 0 ; j < n; j++) { if (i == j) continue ; if (arr[j] <= arr[i]) { closest = Math.max(closest, arr[j]); } } if ( closest == Integer.MIN_VALUE) res.add(- 1 ); else res.add(closest); } return res; } public static void main(String[] args) { int [] arr = { 6 , 11 , 7 , 8 , 20 , 12 }; int n = arr.length; List<Integer> result = closestSmallerOrSame(arr, n); for ( int i = 0 ; i < result.size(); i++) System.out.print(result.get(i) + " " ); System.out.println(); } } |
Python
def closest_smaller_or_same(arr): n = len (arr) res = [] for i in range (n): closest = float ( '-inf' ) for j in range (n): if i = = j: continue if arr[j] < = arr[i]: closest = max (closest, arr[j]) if closest = = float ( '-inf' ): res.append( - 1 ) else : res.append(closest) return res arr = [ 6 , 11 , 7 , 8 , 20 , 12 ] result = closest_smaller_or_same(arr) print ' ' .join( map ( str , result)) |
C#
using System; using System.Collections.Generic; public class Program { public static List< int > ClosestSmallerOrSame( int [] arr, int n) { List< int > res = new List< int >(); for ( int i = 0; i < n; i++) { int closest = int .MinValue; for ( int j = 0; j < n; j++) { if (i == j) continue ; if (arr[j] <= arr[i]) { closest = Math.Max(closest, arr[j]); } } if (closest == int .MinValue) res.Add(-1); else res.Add(closest); } return res; } public static void Main() { int [] arr = { 6, 11, 7, 8, 20, 12 }; int n = arr.Length; List< int > result = ClosestSmallerOrSame(arr, n); foreach ( var item in result) { Console.Write(item + " " ); } Console.WriteLine(); } } |
Javascript
function closestSmallerOrSame(arr) { const n = arr.length; const res = []; for (let i = 0; i < n; i++) { let closest = Number.MIN_SAFE_INTEGER; for (let j = 0; j < n; j++) { if (i === j) { continue ; } if (arr[j] <= arr[i]) { closest = Math.max(closest, arr[j]); } } if (closest === Number.MIN_SAFE_INTEGER) { res.push(-1); } else { res.push(closest); } } return res; } const arr = [6, 11, 7, 8, 20, 12]; const result = closestSmallerOrSame(arr); console.log(result.join( " " )); |
Time Complexity: O(N*N) as two nested loops are executing. Here, N is size of the input array.
Space Complexity: O(1) as no extra space has been used. Note here res vector space is ignored as it is the resultnt vector.
A better solution is to sort the array and create a sorted copy, then do a binary search for floor. We traverse the array, for every element we search for the first occurrence of an element that is greater than or equal to given element. Once we find such an element, we check if the next of it is also the same, if yes, then there are multiple occurrences of the element, so we print the same element as output. Otherwise, we print previous element in the sorted array. In C++, lower_bound() returns iterator to the first greater or equal element in a sorted array.
Implementation:
C++
#include <bits/stdc++.h> using namespace std; void printPrevGreater( int arr[], int n) { vector< int > v(arr, arr + n); sort(v.begin(), v.end()); for ( int i = 0; i < n; i++) { if (arr[i] == v[0]) { (arr[i] == v[1]) ? cout << arr[i] : cout << -1; cout << " " ; continue ; } auto it = lower_bound(v.begin(), v.end(), arr[i]); if (it != v.end() && *(it + 1) == arr[i]) cout << arr[i] << " " ; else cout << *(it - 1) << " " ; } } int main() { int arr[] = { 6, 11, 7, 8, 20, 12 }; int n = sizeof (arr) / sizeof (arr[0]); printPrevGreater(arr, n); return 0; } |
Java
import java.io.*; import java.util.*; class GFG { static int count( int [] arr, int target) { int count = 0 ; for ( int i = 0 ; i < arr.length; i++) { if (arr[i] == target) { count++; } } return count; } static int index( int [] arr, int target) { int index = - 1 ; for ( int i = 0 ; i < arr.length; i++) { if (arr[i] == target) { return i; } } return index; } static void printPrevGreater( int [] arr, int n) { int [] v = new int [n]; for ( int i = 0 ; i < n; i++) { v[i] = arr[i]; } Arrays.sort(v); int it = 0 ; for ( int i = 0 ; i < n; i++) { if (arr[i] == v[ 0 ]) { System.out.print( ((arr[i] == v[ 1 ]) ? arr[i] : - 1 ) + " " ); continue ; } if (count(arr, arr[i]) > 0 ) { it = v[index(v, arr[i])]; } else { it = v[n - 1 ]; } if (it != v[n - 1 ] && v[index(v, it) + 1 ] == arr[i]) { System.out.print(arr[i] + " " ); } else { System.out.print(v[index(v, it) - 1 ] + " " ); } } } public static void main(String[] args) { int [] arr = { 6 , 11 , 7 , 8 , 20 , 12 }; int n = arr.length; printPrevGreater(arr, n); } } |
Python3
def printPrevGreater(arr, n) : v = arr.copy() v.sort() for i in range (n) : if (arr[i] = = v[ 0 ]) : if (arr[i] = = v[ 1 ]) : print (arr[i], end = " " ) else : print ( - 1 , end = " " ) continue if v.count(arr[i]) > 0 : it = v[v.index(arr[i])] else : it = v[n - 1 ] if (it ! = v[n - 1 ] and v[v.index(it) + 1 ] = = arr[i]) : print (arr[i], end = " " ) else : print (v[v.index(it) - 1 ], end = " " ) if __name__ = = "__main__" : arr = [ 6 , 11 , 7 , 8 , 20 , 12 ] n = len (arr) printPrevGreater(arr, n) |
C#
using System; using System.Collections; public class GFG { static int count( int [] arr, int target) { int count = 0; for ( int i = 0; i < arr.Length; i++) { if (arr[i] == target) { count++; } } return count; } static int index( int [] arr, int target) { int index = -1; for ( int i = 0; i < arr.Length; i++) { if (arr[i] == target) { return i; } } return index; } static void printPrevGreater( int [] arr, int n) { int [] v = new int [n]; for ( int i = 0; i < n; i++) { v[i] = arr[i]; } Array.Sort(v); int it = 0; for ( int i = 0; i < n; i++) { if (arr[i] == v[0]) { Console.Write( ((arr[i] == v[1]) ? arr[i] : -1) + " " ); continue ; } if (count(arr, arr[i]) > 0) { it = v[index(v, arr[i])]; } else { it = v[n - 1]; } if (it != v[n - 1] && v[index(v, it) + 1] == arr[i]) { Console.Write(arr[i] + " " ); } else { Console.Write(v[index(v, it) - 1] + " " ); } } } static public void Main() { int [] arr = { 6, 11, 7, 8, 20, 12 }; int n = arr.Length; printPrevGreater(arr, n); } } |
Javascript
<script> function printPrevGreater(arr, n) { let v = [...arr] v.sort((a, b) => a - b); for (let i = 0; i < n; i++) { if (arr[i] == v[0]) { (arr[i] == v[1]) ? document.write(arr[i]) : document.write(-1); document.write( " " ); continue ; } if (v.includes(arr[i])) it = v[v.indexOf(arr[i])] else it = v[n - 1] if (it != v[n - 1] && (v[v.indexOf(it) + 1] == arr[i])) document.write(arr[i] + " " ); else document.write(v[v.indexOf(it) - 1] + " " ); } } function lower_bound(arr, val){ } let arr = [ 6, 11, 7, 8, 20, 12 ]; let n = arr.length; printPrevGreater(arr, n); </script> |
Complexity Analysis:
- Time Complexity: O(n Log n)
- Auxiliary Space: O(n)
Similar Reads
Ceiling of every element in same array
Given an array of integers, find the closest greater or same element for every element. If all elements are smaller for an element, then print -1 Examples: Input : arr[] = {10, 5, 11, 10, 20, 12} Output : 10 10 12 10 -1 20 Note that there are multiple occurrences of 10, so ceiling of 10 is 10 itself
15+ min read
Ceiling in right side for every element in an array
Given an array of integers, find the closest greater element for every element. If there is no greater element then print -1 Examples: Input : arr[] = {10, 5, 11, 10, 20, 12} Output : 10 10 12 12 -1 -1 Input : arr[] = {50, 20, 200, 100, 30} Output : 100 30 -1 -1 -1 A simple solution is to run two ne
4 min read
Frequency of an element in an array
Given an array, a[], and an element x, find a number of occurrences of x in a[]. Examples: Input : a[] = {0, 5, 5, 5, 4} x = 5Output : 3Input : a[] = {1, 2, 3} x = 4Output : 0 Unsorted ArrayThe idea is simple, we initialize count as 0. We traverse the array in a linear fashion. For every element tha
9 min read
Range Queries for Frequencies of array elements
Given an array of n non-negative integers. The task is to find frequency of a particular element in the arbitrary range of array[]. The range is given as positions (not 0 based indexes) in array. There can be multiple queries of given type. Examples: Input : arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11}; lef
13 min read
All elements in an array are Same or not?
Given an array, check whether all elements in an array are the same or not. Examples: Input : "Geeks", "for", "Geeks" Output : Not all Elements are Same Input : 1, 1, 1, 1, 1 Output : All Elements are Same Method 1 (Hashing): We create an empty HashSet, insert all elements into it, then we finally s
5 min read
Missing Elements of a Range in an Array
Given an array of size N. Let min and max be the minimum and maximum in the array respectively. Task is to find how many number should be added to the given array such that all the element in the range [min, max] occur at-least once in the array. Examples: Input : arr[] = {4, 5, 3, 8, 6}Output : 1On
7 min read
Least frequent element in an array
Given an array, find the least frequent element in it. If there are multiple elements that appear least number of times, print any one of them. Examples : Input : arr[] = {1, 3, 2, 1, 2, 2, 3, 1}Output : 3Explanation: 3 appears minimum number of times in given array. Input : arr[] = {10, 20, 30}Outp
12 min read
Elements that occurred only once in the array
Given an array arr that has numbers appearing twice or once. The task is to identify numbers that occur only once in the array. Note: Duplicates appear side by side every time. There might be a few numbers that can occur at one time and just assume this is a right rotating array (just say an array c
15+ min read
Find the frequency of each element in a sorted array
Given a sorted array, arr[] consisting of N integers, the task is to find the frequencies of each array element. Examples: Input: arr[] = {1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10} Output: Frequency of 1 is: 3 Frequency of 2 is: 1 Frequency of 3 is: 2 Frequency of 5 is: 2 Frequency of 8 is: 3 Frequ
10 min read
Floor in a Sorted Array
Given a sorted array and a value x, find the element of the floor of x. The floor of x is the largest element in the array smaller than or equal to x. Examples: Input: arr[] = [1, 2, 8, 10, 10, 12, 19], x = 5Output: 1Explanation: Largest number less than or equal to 5 is 2, whose index is 1 Input: a
9 min read