Count elements in Array having strictly smaller and strictly greater element present

Given an array arr[], the task is to find the count of elements in the given array such that there exists an element strictly smaller and an element strictly greater than it.
Examples:
Input: arr [] = {11, 7, 2, 15}
Output: 2
Explanation: For arr[1] = 7, arr[0] is strictly greater than it and arr[2] is strictly smaller than it. Similarly for arr[1], arr[3] is strictly greater than it and arr[2] is strictly smaller than it. Hence, the required count is 2.Input: arr[] = {1, 1, 1, 3}
Output: 0
Naive Approach: The given problem can be solved by iterating over each element of the array arr[] and checking whether there exists a strictly greater and strictly smaller element than it.
Algorithm:
-  Initialize a variable ‘count‘ to 0 to keep track of the number of elements that satisfy the condition.
-  Traverse each element of the array using a loop with index ‘i’.
-  For each element, traverse the array again using a nested loop with index ‘j’ and check if there exists an element strictly smaller and an   element strictly greater than the current element arr[i].
-  If such elements exist, increase the ‘count‘ variable.
-  Return the final value of ‘count‘.
Below is the implementation of the approach:
C++
// C++ code for the approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to count elements// which satisfy the conditionint countElements(int arr[], int n) {    int count = 0;         // traverse each element    for (int i = 0; i < n; i++) {        bool smaller = false, greater = false;        for (int j = 0; j < n; j++) {            if (i != j) {                if (arr[j] < arr[i])                    smaller = true;                else if (arr[j] > arr[i])                    greater = true;            }        }                     // if both strictly smaller and          // greater exists, increase count        if (smaller && greater)            count++;    }       return count;}Â
// Driver's codeint main() {    // Input    int arr[] = { 11, 7, 2, 15 };    int n = sizeof(arr) / sizeof(arr[0]);       // Function call    int count = countElements(arr, n);Â
    // Output    cout << count;Â
    return 0;} |
Java
public class Main {    // Function to count elements that satisfy the condition    public static int countElements(int[] arr) {        int n = arr.length;        int count = 0;Â
        // Loop through each element        for (int i = 0; i < n; i++) {            boolean smaller = false, greater = false;Â
            for (int j = 0; j < n; j++) {                if (i != j) {                    if (arr[j] < arr[i])                        smaller = true;                    else if (arr[j] > arr[i])                        greater = true;                }            }Â
            // If both strictly smaller and greater elements exist, increase count            if (smaller && greater)                count++;        }Â
        return count;    }Â
    public static void main(String[] args) {        // Input        int[] arr = { 11, 7, 2, 15 };Â
        // Function call        int count = countElements(arr);Â
        // Output        System.out.println(count);    }} |
Python3
def count_elements(arr):Â Â Â Â count = 0Â
    # Traverse each element    for i in range(len(arr)):        smaller, greater = False, False        for j in range(len(arr)):            if i != j:                if arr[j] < arr[i]:                    smaller = True                elif arr[j] > arr[i]:                    greater = TrueÂ
        # If both strictly smaller and greater elements exist, increase count        if smaller and greater:            count += 1Â
    return countÂ
# Driver's codearr = [11, 7, 2, 15]count = count_elements(arr)print(count) |
C#
using System;Â
public class GFG {    // Function to count elements    // which satisfy the condition    public static int CountElements(int[] arr, int n)    {        int count = 0;Â
        // traverse each element        for (int i = 0; i < n; i++) {            bool smaller = false, greater = false;            for (int j = 0; j < n; j++) {                if (i != j) {                    if (arr[j] < arr[i])                        smaller = true;                    else if (arr[j] > arr[i])                        greater = true;                }            }Â
            // if both strictly smaller and            // greater exists, increase count            if (smaller && greater)                count++;        }Â
        return count;    }Â
    public static void Main()    {        // Input        int[] arr = { 11, 7, 2, 15 };        int n = arr.Length;Â
        // Function call        int count = CountElements(arr, n);Â
        // Output        Console.WriteLine(count);    }} |
Javascript
// JS code for the approachÂ
// Function to count elements// which satisfy the conditionfunction countElements(arr, n) {    let count = 0;         // traverse each element    for (let i = 0; i < n; i++) {        let smaller = false, greater = false;        for (let j = 0; j < n; j++) {            if (i != j) {                if (arr[j] < arr[i])                    smaller = true;                else if (arr[j] > arr[i])                    greater = true;            }        }                     // if both strictly smaller and          // greater exists, increase count        if (smaller && greater)            count++;    }       return count;}Â
// Driver's code// Inputlet arr = [ 11, 7, 2, 15 ];let n = arr.length;Â
// Function calllet count = countElements(arr, n);Â
// Outputconsole.log(count); |
2
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized by finding the minimum and maximum element of the given array, traversing the given array arr[], and checking if arr[i] is strictly greater than the minimum and strictly smaller than the maximum. Maintain the count of such indices in a variable which is the required answer.
Below is the implementation of the above approach:
C++
// C++ Program of the above approach#include <bits/stdc++.h>using namespace std;Â
// Function to find the count of elements// in the given array such that there exists// a strictly smaller and greater elementint cntElements(vector<int>& arr){    // Stores the maximum    int a = *max_element(        arr.begin(), arr.end());Â
    // Stores the minimum    int b = *min_element(        arr.begin(), arr.end());Â
    // Stores the required count    int cnt = 0;Â
    // Loop to iterate arr[]    for (auto x : arr) {        // If x is valid        if (x < a && x > b)            cnt++;    }Â
    // Return Answer    return cnt;}Â
// Driver Codeint main(){Â Â Â Â vector<int> arr = { 11, 7, 2, 15 };Â Â Â Â cout << cntElements(arr);Â
    return 0;} |
Java
// Java Program of the above approachimport java.util.*;public class GFG {Â
  // Function to find the count of elements  // in the given array such that there exists  // a strictly smaller and greater element  static int cntElements(int[] arr)  {Â
    // Stores the required count    int cnt = 0;Â
    // Stores the maximum    int a = arr[0];Â
    // Stores the minimum    int b = arr[0];    for (int i = 1; i < arr.length; i++) {Â
      if (arr[i] > a) {        a = arr[i];      }Â
      if (arr[i] < b) {        b = arr[i];      }    }    // Loop to iterate arr[]    for (int i = 0; i < arr.length; i++) {Â
      // If x is valid      if (arr[i] < a && arr[i] > b)        cnt++;    }Â
    // Return Answer    return cnt;  }Â
  // Driver Code  public static void main(String args[])  {    int[] arr = { 11, 7, 2, 15 };    System.out.print(cntElements(arr));Â
  }}Â
// This code is contributed by Samim Hossain Mondal. |
Python3
# Python code for the above approachÂ
# Function to find the count of elements# in the given array such that there exists# a strictly smaller and greater elementdef cntElements(arr):Â
    # Stores the maximum    a = max(arr)Â
    # Stores the minimum    b =min(arr)Â
    # Stores the required count    cnt = 0Â
    # Loop to iterate arr[]    for x in range(len(arr)):        # If x is valid        if arr[x] < a and arr[x]> b:            cnt = cnt + 1         # Return Answer    return cntÂ
# Driver Codearr = [11, 7, 2, 15];print(cntElements(arr));Â Â Â Â # This code is contributed by Potta Lokesh |
C#
// C# Program of the above approachusing System;class GFG {Â
  // Function to find the count of elements  // in the given array such that there exists  // a strictly smaller and greater element  static int cntElements(int[] arr)  {Â
    // Stores the required count    int cnt = 0;Â
    // Stores the maximum    int a = arr[0];Â
    // Stores the minimum    int b = arr[0];    for (int i = 1; i < arr.Length; i++) {Â
      if (arr[i] > a) {        a = arr[i];      }Â
      if (arr[i] < b) {        b = arr[i];      }    }    // Loop to iterate arr[]    for (int i = 0; i < arr.Length; i++) {Â
      // If x is valid      if (arr[i] < a && arr[i] > b)        cnt++;    }Â
    // Return Answer    return cnt;  }Â
  // Driver Code  public static int Main()  {    int[] arr = { 11, 7, 2, 15 };    Console.Write(cntElements(arr));Â
    return 0;  }}Â
// This code is contributed by Taranpreet |
Javascript
<script>Â Â Â Â // JavaScript Program of the above approachÂ
    // Function to find the count of elements    // in the given array such that there exists    // a strictly smaller and greater element    const cntElements = (arr) => {        // Stores the maximum        let a = Math.max(...arr);Â
        // Stores the minimum        let b = Math.min(...arr);Â
        // Stores the required count        let cnt = 0;Â
        // Loop to iterate arr[]        for (let x in arr) {            // If x is valid            if (arr[x] < a && arr[x] > b)                cnt++;        }Â
        // Return Answer        return cnt;    }Â
    // Driver CodeÂ
    let arr = [11, 7, 2, 15];    document.write(cntElements(arr));Â
// This code is contributed by rakeshsahniÂ
</script> |
2
Time Complexity: O(N)
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



