Leetcode 1299. Replace Elements with Greatest Element on Right Side
Given an array arr
, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1
.
You need to solve it with O(n) time complexity.
This approach ensures we only traverse the array once linearly, achieving the desired time complexity of O(n).
#include <vector>
#include <iostream>
using namespace std;
vector<int> replaceElements(vector<int>& arr) {
int n = arr.size();
int maxRight = -1;
// Iterate from right to left
for (int i = n - 1; i >= 0; --i) {
int current = arr[i];
arr[i] = maxRight;
if (current > maxRight) {
maxRight = current;
}
}
return arr;
}
// Function to print the array for debugging purposes
void printArray(const vector<int>& arr) {
for (int val : arr) {
cout << val << " ";
}
cout << endl;
}
// Example usage
int main() {
vector<int> arr = {17, 18, 5, 4, 6, 1};
vector<int> result = replaceElements(arr);
printArray(result); // Expected output: [18, 6, 6, 6, 1, -1]
return 0;
}
maxRight
).This solution is optimal in terms of both time and space complexity.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?