Find the lexicographically largest array containing all distinct elements from each prefix of the given array
Last Updated :
11 Jan, 2024
Given an array arr[] of length N. The task is to find a lexicographically largest array res[] of the same length such that each prefix of res[] includes all distinct elements present in the corresponding prefix of array arr[].
Examples:
Input: N = 6, arr[] = {2, 5, 3, 2, 6, 5}
Output: res[] = {2, 5, 3, 6, 6, 6}
Explanation: This can be verified that each distinct element of arr[] is present at least once in res[]. Along with this let us analyze each prefix of arr[] for second condition:
- arr[1, 1] = {2}, res[1, 1] = {2}. Each element of prefix arr[] is present at least once in res[]
- arr[1, 2] = {2, 5}, res[1, 2] = {2, 5}. Each element of prefix arr[] is present at least once in res[]
- arr[1, 3] = {2, 5, 3}, res[1, 3] = {2, 5, 3}. Each element of prefix arr[] is present at least once in res[]
- arr[1, 4] = {2, 5, 3, 6} res[1, 4] = {2, 5, 3, 6}. Each element of prefix arr[] is present at least once in res[]
- arr[1, 5] = {2, 5, 3, 6, 6}, res[1, 5] = {2, 5, 3, 6, 6}. Each element of prefix arr[] is present at least once in res[]
- arr[1, 6] = {2, 5, 3, 6, 6, 6}, res[1, 6] = {2, 5, 3, 6, 6, 6}. Each element of prefix arr[] is present at least once in res[]
It can be verified that both the conditions met and res[] is also lexographically largest. Thus, res[] is valid.
Input: N = 4, arr[] = {5, 5, 2, 7}
Output: res[] = {5, 7, 2, 7}
Explanation: It can be verified that res[] is lexographically largest following the condition that each prefix of res[1, i] contains each element of arr[1, i] for all i (1 <= i <=N) at least once.
Approach:
According to the problem, it is given that every element in the prefix arr[] should be present at least once in res[]. So, in the case of multiple occurrences of any element of arr, we need to replace that with the maximum element in arr to make it lexicographically highest. Anyway, it is present once, so for the rest of the occurrences, we can make them to maximum.
Steps-by-step approach:
- Create a result array res[] to store the required order of all elements following given constraints.
- Create a HashMap Map to keep track of occurrences of elements of arr[].
- Create a variable M and initialize it with maximum element of arr[].
- Iterate on arr[] using loop and follow below-mentioned steps under the scope of loop:
- If (arr[i] element is not present in Map)
- Insert element into res[].
- Otherwise,
- Insert the maximum element (M) of the array arr[] into res[].
- Increment the frequency of arr[i] element.
- Output all the elements stored in res[].
Below is the implementation of the above approach:
C++
// C++ program to implement the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the
// lexicographically largest array res[]
void MaxLexographicalY(int arr[], int N)
{
// Vector to store the order of elements
// Following the given constraints
vector<int> res;
// to keep track of occurrances in array A
unordered_map<int, int> count;
// m is max element of A
int m = *max_element(arr, arr + N);
for (int i = 0; i < N; i++) {
// if element A[i] not present in map
if (!count[arr[i]]) {
res.push_back(arr[i]);
}
else {
res.push_back(m);
}
count[arr[i]]++;
}
// Printing out all stored elements
for (int i = 0; i < res.size(); i++) {
cout << res[i] << ' ';
}
}
// Driver Code
int main()
{
// Input
int N = 4;
int arr[] = { 5, 5, 2, 7 };
// Function Call
MaxLexographicalY(arr, N);
return 0;
}
Java
/*code by Flutterfly */
import java.util.ArrayList;
import java.util.HashMap;
public class MaxLexographicalY {
// Function to find the lexicographically largest array res[]
static void maxLexographicalY(int[] arr, int N) {
// ArrayList to store the order of elements
// Following the given constraints
ArrayList<Integer> res = new ArrayList<>();
// HashMap to keep track of occurrences in array A
HashMap<Integer, Integer> count = new HashMap<>();
// m is the max element of A
int m = Integer.MIN_VALUE;
for (int value : arr) {
m = Math.max(m, value);
}
for (int i = 0; i < N; i++) {
// if element A[i] not present in map
if (!count.containsKey(arr[i])) {
res.add(arr[i]);
} else {
res.add(m);
}
count.put(arr[i], count.getOrDefault(arr[i], 0) + 1);
}
// Printing out all stored elements
for (int i = 0; i < res.size(); i++) {
System.out.print(res.get(i) + " ");
}
}
// Driver Code
public static void main(String[] args) {
// Input
int N = 4;
int[] arr = {5, 5, 2, 7};
// Function Call
maxLexographicalY(arr, N);
}
}
Python3
# code by flutterfly
from collections import defaultdict
# Function to find the lexicographically largest array res[]
def max_lexographical_y(arr, N):
# List to store the order of elements
# Following the given constraints
res = []
# Dictionary to keep track of occurrences in array A
count = defaultdict(int)
# m is the max element of A
m = max(arr)
for i in range(N):
# if element A[i] not present in map
if not count[arr[i]]:
res.append(arr[i])
else:
res.append(m)
count[arr[i]] += 1
# Printing out all stored elements
for i in range(len(res)):
print(res[i], end=' ')
# Driver Code
if __name__ == "__main__":
# Input
N = 4
arr = [5, 5, 2, 7]
# Function Call
max_lexographical_y(arr, N)
C#
// code by flutterfly
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
// Function to find the lexicographically largest array res[]
static void MaxLexographicalY(int[] arr, int N)
{
// List to store the order of elements
// Following the given constraints
List<int> res = new List<int>();
// Dictionary to keep track of occurrences in array A
Dictionary<int, int> count = new Dictionary<int, int>();
// m is the max element of A
int m = arr.Max();
for (int i = 0; i < N; i++)
{
// if element A[i] not present in map
if (!count.ContainsKey(arr[i]))
{
res.Add(arr[i]);
}
else
{
res.Add(m);
}
count[arr[i]] = count.GetValueOrDefault(arr[i]) + 1;
}
// Printing out all stored elements
foreach (int element in res)
{
Console.Write(element + " ");
}
}
// Driver Code
static void Main()
{
// Input
int N = 4;
int[] arr = { 5, 5, 2, 7 };
// Function Call
MaxLexographicalY(arr, N);
}
}
JavaScript
//code by Flutterfly
// Function to find the lexicographically largest array res[]
function maxLexographicalY(arr, N) {
// Array to store the order of elements
// Following the given constraints
let res = [];
// Map to keep track of occurrences in array A
let count = new Map();
// m is the max element of A
let m = Math.max(...arr);
for (let i = 0; i < N; i++) {
// if element A[i] not present in map
if (!count.has(arr[i])) {
res.push(arr[i]);
} else {
res.push(m);
}
count.set(arr[i], (count.get(arr[i]) || 0) + 1);
}
// Printing out all stored elements on the same line with spaces
console.log(res.join(' '));
}
// Driver Code
function main() {
// Input
let N = 4;
let arr = [5, 5, 2, 7];
// Function Call
maxLexographicalY(arr, N);
}
// Invoke the main function
main();
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Lexicographical smallest and largest Permutation from Array whose elements are max of Prefix Given an array A[] of size N where each element A[i] =max(P[0], P[1], . . ., P[i]), where P[] is a permutation consisting of elements from 1 to N, the task is to find the lexicographically smallest and lexicographically largest permutation that satisfies A[]. Examples: Input: A[] = {3, 4, 5, 5, 5, 7
10 min read
Lexicographically largest subsequence containing all distinct characters only once Given a string S, the task is to find the lexicographically largest subsequence that can be formed using all distinct characters only once from the given string. Examples: Input: S = ababcOutput: bacExplanation:All possible subsequences containing all the characters in S exactly once are {"abc", "ba
8 min read
Queries to find the maximum array element after removing elements from a given range Given an array arr[] and an array Q[][] consisting of queries of the form of {L, R}, the task for each query is to find the maximum array element after removing array elements from the range of indices [L, R]. If the array becomes empty after removing the elements from given range of indices, then p
10 min read
Find permutation which generates lexicographically largest Array of GCD of Prefixes Given an array A[] of size N, find the permutation of array A such that the array B[] which is formed by taking the GCD of the prefixes of array A is lexicographically greatest among all possible arrays. Print the permutation of A and also B. Note: If multiple answers are possible, print any of them
15+ min read
Lexicographically largest string for given dictionary order Given an array arr[] of N strings and a string order which represents the new alphabetical order of the string. The task is to find the lexicographically largest string based on the given order. Examples: Input: arr[] = {"abc", "abd", "abz"}, order = "abczdefghijklmnopqrstuvwxy" Output: abd Explanat
14 min read