Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Replace every element with the greatest element on its left side
Next article icon

Replace every element with the smallest element on its left side

Last Updated : 17 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array of integers, the task is to replace every element with the smallest element on its left side. 

Note: Replace the first element with -1 as it has no element in its left. 

Examples: 

Input: arr[] = {4, 5, 2, 1, 7, 6} Output: -1 4 4 2 1 1 Since, 4 has no element in its left, so replace it by -1. For 5, 4 is the smallest element in its left. For 2, 4 is the smallest element in its left. For 1, 2 is the smallest element in its left. For 7, 1 is the smallest element in its left. For 6, 1 is the smallest element in its left.  Input: arr[] = {3, 2, 5, 7, 1} Output: -1 3 2 2 2

Approach: 

  1. Maintain a variable min_ele which will store the smallest element.
  2. Initially, min_ele will be equal to the element at the 0th index.
  3. First replace arr[0] with -1 then traverse the array
  4. And then replace the element with the min_ele value and update the min_ele if the element is smaller than min_ele.
  5. Print the modified array.

Below is the implementation of the above approach: 

C++
// C++ program to Replace every // element with the smaller element // on its left side #include <bits/stdc++.h> using namespace std;  // Function to replace the elements void ReplaceElements(int arr[], int n) {     // MIN value initialised     // to element at 0th index     int min_ele = arr[0];     arr[0] = -1;      for (int i = 1; i < n; ++i) {          // If min_ele is smaller than arr[i]         // then just replace arr[i] with min_ele         if (min_ele < arr[i])             arr[i] = min_ele;           // Else if update the min_ele also         else if (min_ele >= arr[i]) {             int temp = arr[i];             arr[i] = min_ele;             min_ele = temp;         }     } }  // Driver code int main() {     int arr[] = { 4, 5, 2, 1, 7, 6 };     int n = sizeof(arr) / sizeof(arr[0]);      // Replace the elements     // with the smaller element     // on its left side     ReplaceElements(arr, n);      // Print the modified array     for (int i = 0; i < n; ++i)         cout << arr[i] << " ";      return 0; } 
Java
// Java program to Replace every  // element with the smaller element  // on its left side   class GFG {  // Function to replace the elements      static void ReplaceElements(int arr[], int n) {         // MIN value initialised          // to element at 0th index          int min_ele = arr[0];         arr[0] = -1;          for (int i = 1; i < n; ++i) {              // If min_ele is smaller than arr[i]              // then just replace arr[i] with min_ele              if (min_ele < arr[i]) {                 arr[i] = min_ele;             } // Else if update the min_ele also              else if (min_ele >= arr[i]) {                 int temp = arr[i];                 arr[i] = min_ele;                 min_ele = temp;             }         }     }  // Driver code      public static void main(String[] args) {         int arr[] = {4, 5, 2, 1, 7, 6};         int n = arr.length;          // Replace the elements          // with the smaller element          // on its left side          ReplaceElements(arr, n);          // Print the modified array          for (int i = 0; i < n; ++i) {             System.out.print(arr[i] + " ");         }     } }  // This code is contributed by Rajput-JI  
Python3
# Python3 program to Replace every # element with the smaller element # on its left side  # Function to replace the elements def ReplaceElements(arr, n):      # MIN value initialised     # to element at 0th index     min_ele = arr[0]     arr[0] = -1      for i in range(1, n):          # If min_ele is smaller than arr[i]         # then just replace arr[i] with min_ele         if (min_ele < arr[i]):             arr[i] = min_ele          # Else if update the min_ele also         elif (min_ele >= arr[i]) :             temp = arr[i]             arr[i] = min_ele             min_ele = temp  # Driver code if __name__ == "__main__":      arr = [ 4, 5, 2, 1, 7, 6 ]     n = len (arr)      # Replace the elements     # with the smaller element     # on its left side     ReplaceElements(arr, n)      # Print the modified array     for i in range( n):         print (arr[i], end = " ")  # This code is contributed # by ChitraNayal 
C#
// C# program to Replace every  // element with the smaller element  // on its left side  using System; public class GFG {   // Function to replace the elements      static void ReplaceElements(int []arr, int n) {         // MIN value initialised          // to element at 0th index          int min_ele = arr[0];         arr[0] = -1;          for (int i = 1; i < n; ++i) {              // If min_ele is smaller than arr[i]              // then just replace arr[i] with min_ele              if (min_ele < arr[i]) {                 arr[i] = min_ele;             } // Else if update the min_ele also              else if (min_ele >= arr[i]) {                 int temp = arr[i];                 arr[i] = min_ele;                 min_ele = temp;             }         }     }  // Driver code      public static void Main() {         int []arr = {4, 5, 2, 1, 7, 6};         int n = arr.Length;          // Replace the elements          // with the smaller element          // on its left side          ReplaceElements(arr, n);          // Print the modified array          for (int i = 0; i < n; ++i) {             Console.Write(arr[i] + " ");         }     } }  // This code is contributed by Rajput-JI  
PHP
<?php // PHP program to Replace every // element with the smaller element // on its left side  // Function to replace the elements function ReplaceElements($arr, $n) {     // MIN value initialised     // to element at 0th index     $min_ele = $arr[0];     $arr[0] = -1;      for ($i = 1; $i < $n; ++$i)      {          // If min_ele is smaller than arr[i]         // then just replace arr[i] with min_ele         if ($min_ele < $arr[$i])             $arr[$i] = $min_ele;          // Else if update the min_ele also         else if ($min_ele >= $arr[$i])         {             $temp = $arr[$i];             $arr[$i] = $min_ele;             $min_ele = $temp;         }     }     return $arr; }  // Driver code $arr = array(4, 5, 2, 1, 7, 6); $n = sizeof($arr);  // Replace the elements // with the smaller element // on its left side $arr1 = ReplaceElements($arr, $n);  // Print the modified array for ($i = 0; $i < $n; ++$i)     echo $arr1[$i] . " ";  // This code is contributed  // by Akanksha Rai ?> 
JavaScript
<script>       // JavaScript program to Replace every       // element with the smaller element       // on its left side        // Function to replace the elements       function ReplaceElements(arr, n)        {                // MIN value initialised         // to element at 0th index         var min_ele = arr[0];         arr[0] = -1;          for (var i = 1; i < n; ++i)          {                    // If min_ele is smaller than arr[i]           // then just replace arr[i] with min_ele           if (min_ele < arr[i]) arr[i] = min_ele;           // Else if update the min_ele also           else if (min_ele >= arr[i])            {             var temp = arr[i];             arr[i] = min_ele;             min_ele = temp;           }         }       }        // Driver code       var arr = [4, 5, 2, 1, 7, 6];       var n = arr.length;        // Replace the elements       // with the smaller element       // on its left side       ReplaceElements(arr, n);        // Print the modified array       for (var i = 0; i < n; ++i) document.write(arr[i] + " ");              // This code is contributed by rdtank.     </script> 

Output
-1 4 4 2 1 1 

Time Complexity: O(N)

Auxiliary Space: O(1) because constant space is being used for variables


Next Article
Replace every element with the greatest element on its left side
author
imdhruvgupta
Improve
Article Tags :
  • Technical Scripter
  • DSA
  • Arrays
  • Technical Scripter 2018
  • array-traversal-question
Practice Tags :
  • Arrays

Similar Reads

  • Replace every element with the greatest element on its left side
    Given an array of integers, the task is to replace every element with the greatest element on its left side. Note: Replace the first element with -1 as it has no element in its left. Examples: Input: arr[] = {4, 5, 2, 1, 7, 6}Output: -1 4 5 5 5 7Explanation:Since, 4 has no element in its left, so re
    6 min read
  • Replace every element with the least greater element on its right
    Given an array of integers, replace every element with the least greater element on its right side in the array. If there are no greater elements on the right side, replace it with -1. Examples: Input: [8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28]Output: [18, 63, 80, 25, 32, 43, 80, 93,
    15+ min read
  • Replace every element with the greatest element on right side
    Given an array of integers, replace every element with the next greatest element (greatest element on the right side) in the array. Since there is no element next to the last element, replace it with -1. For example, if the array is {16, 17, 4, 3, 5, 2}, then it should be modified to {17, 5, 5, 5, 2
    11 min read
  • Replace every element with the smallest of all other array elements
    Given an array arr[] which consist of N integers, the task is to replace every element by the smallest of all other elements present in the array. Examples: Input: arr[] = {1, 1, 1, 2} Output: 1 1 1 1 Input: arr[] = {4, 2, 1, 3} Output: 1 1 2 1 Naive Approach: The simplest approach is to find the sm
    12 min read
  • Replace every element with the smallest of the others
    Given an array arr[] of N distinct integers, the task is to replace every element by smallest among all other remaining elements of the array.Examples: Input: arr[] = { 4, 2, 1, 3 } Output: arr[]= { 1, 1, 2, 1 } Explanation: For arr[0], the smallest out of the remaining elements is 1. So arr[0] is r
    6 min read
  • Replace elements with absolute difference of smallest element on left and largest element on right
    Given an array arr[] of N integers. The task is to replace all the elements of the array by the absolute difference of the smallest element on its left and the largest element on its right.Examples: Input: arr[] = {1, 5, 2, 4, 3} Output: 5 3 3 2 1 ElementSmallest on its leftLargest on its rightAbsol
    15+ min read
  • Make all array elements equal by repeatedly replacing largest array element with the second smallest element
    Given an array arr[] of size N, the task is to count the number of operations required to make all array elements equal by replacing the largest array element with the second-largest array element, which is strictly smaller than the largest array element. Examples: Input: arr[ ] = {1, 1, 2, 2, 3}Out
    6 min read
  • Count smaller elements on right side and greater elements on left side using Binary Index Tree
    Given an array arr[] of size N. The task is to find smaller elements on the right side and greater elements on the left side for each element arr[i] in the given array. Examples: Input: arr[] = {12, 1, 2, 3, 0, 11, 4} Output: Smaller right: 6 1 1 1 0 1 0 Greater left: 0 1 1 1 4 1 2 Input: arr[] = {5
    15+ min read
  • Replace diagonal elements in each row of given Matrix by Kth smallest element of that row
    Given a matrix mat[ ][ ] of size N*N and an integer K, containing integer values, the task is to replace diagonal elements by the Kth smallest element of row. Examples: Input: mat[][]= {{1, 2, 3, 4} {4, 2, 7, 6} {3, 5, 1, 9} {2, 4, 6, 8}}K = 2Output: 2, 2, 3, 4 4, 4, 7, 6 3, 5, 3, 8 2, 4, 6, 4Explan
    6 min read
  • Next Greater Element (NGE) for every element in given Array
    Given an array arr[] of integers, the task is to find the Next Greater Element for each element of the array in order of their appearance in the array. Note: The Next Greater Element for an element x is the first greater element on the right side of x in the array. Elements for which no greater elem
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences