Given an array nums[] of N integers the task is to generate a suffix product array from the given array.
A Suffix Product Array is an array where each element at index i contains the product of all elements to the right of i (including the element at index i).
Examples:
Input: nums[] = {1, 2, 3, 4, 5}
Output: {120, 120, 60, 20, 5}
Explanation: {1 * 2 * 3 * 4 * 5, 2 * 3 * 4 * 5, 3 * 4 * 5, 4 * 5, 5} = {120, 120, 60, 20, 5}
Input: nums[] = {3, 2, 1}
Output: {6, 2, 1}
Explanation: {3 * 2 * 1, 2 * 1, 1} = {6, 2, 1}
Approach: To solve the problem, follow the below idea:
The approach involves creating a suffix product array where each element at index i contains the product of all elements to the right of (and including) index i in the original array.
Step-by-step algorithm:
- Initialize a result vector suffixProduct[] with the same size as the input array and set each element to 1 initially.
- It then iterates from the second-last element to the first element of the input array, updating each element in suffixProduct by multiplying it with the next element to the right.
- Print the suffixProduct array as the suffix product array.
Below is the implementation of the approach:
C++
#include <bits/stdc++.h>
using namespace std;
vector<int> calculateSuffixProduct(const vector<int>& nums)
{
int n = nums.size();
vector<int> suffixProduct(n, 1);
for (int i = n - 2; i >= 0; i--) {
suffixProduct[i]
= suffixProduct[i + 1] * nums[i + 1];
}
return suffixProduct;
}
int main()
{
vector<int> inputArray = { 1, 2, 3, 4, 5 };
vector<int> suffixProductArray
= calculateSuffixProduct(inputArray);
// Adjusting each element to include the element at
// index i
for (int i = 0; i < inputArray.size(); i++) {
suffixProductArray[i] *= inputArray[i];
}
for (int product : suffixProductArray) {
cout << product << " ";
}
return 0;
}
Java
import java.util.ArrayList;
import java.util.List;
public class SuffixProduct {
static List<Integer> calculateSuffixProduct(List<Integer> nums) {
int n = nums.size();
List<Integer> suffixProduct = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
suffixProduct.add(1);
}
for (int i = n - 2; i >= 0; i--) {
suffixProduct.set(i, suffixProduct.get(i + 1) * nums.get(i + 1));
}
return suffixProduct;
}
public static void main(String[] args) {
List<Integer> inputArray = List.of(1, 2, 3, 4, 5);
List<Integer> suffixProductArray = calculateSuffixProduct(inputArray);
for (int i = 0; i < inputArray.size(); i++) {
suffixProductArray.set(i, suffixProductArray.get(i) * inputArray.get(i));
}
for (int product : suffixProductArray) {
System.out.print(product + " ");
}
}
}
Python3
def calculate_suffix_product(nums):
n = len(nums)
suffix_product = [1] * n
for i in range(n - 2, -1, -1):
suffix_product[i] = suffix_product[i + 1] * nums[i + 1]
return suffix_product
if __name__ == "__main__":
input_array = [1, 2, 3, 4, 5]
suffix_product_array = calculate_suffix_product(input_array)
# Adjusting each element to include the element at
# index i
for i in range(len(input_array)):
suffix_product_array[i] *= input_array[i]
for product in suffix_product_array:
print(product, end=" ")
# This code is contributed by shivamgupta0987654321
C#
using System;
using System.Collections.Generic;
class Program
{
// Function to calculate the suffix product of an array
static List<int> CalculateSuffixProduct(List<int> nums)
{
int n = nums.Count;
List<int> suffixProduct = new List<int>(n);
// Initialize the last element of the suffix product array
suffixProduct.Add(1);
// Calculate suffix product for each element in the array
for (int i = n - 1; i > 0; i--)
{
// Multiply the current suffix product by the next element
suffixProduct.Insert(0, suffixProduct[0] * nums[i]);
}
return suffixProduct;
}
static void Main()
{
// Input array
List<int> inputArray = new List<int> { 1, 2, 3, 4, 5 };
// Calculate the suffix product for each element in the array
List<int> suffixProductArray = CalculateSuffixProduct(inputArray);
// Adjust each element to include the element at its index
for (int i = 0; i < inputArray.Count; i++)
{
suffixProductArray[i] *= inputArray[i];
}
// Print the final suffix product array
Console.WriteLine("Resulting Suffix Product Array:");
foreach (int product in suffixProductArray)
{
Console.Write(product + " ");
}
Console.ReadLine(); // To keep the console window open
}
}
JavaScript
function calculateSuffixProduct(nums) {
const n = nums.length;
const suffixProduct = new Array(n).fill(1);
for (let i = n - 2; i >= 0; i--) {
suffixProduct[i] = suffixProduct[i + 1] * nums[i + 1];
}
return suffixProduct;
}
function main() {
const inputArray = [1, 2, 3, 4, 5];
const suffixProductArray = calculateSuffixProduct(inputArray);
// Adjusting each element to include the element at
// index i
for (let i = 0; i < inputArray.length; i++) {
suffixProductArray[i] *= inputArray[i];
}
for (const product of suffixProductArray) {
console.log(product);
}
}
main();
Time Complexity: O(N), where N is the size of input array nums[].
Auxiliary Space: O(N)
Similar Reads
Suffix Array | Set 1 (Introduction) We strongly recommend to read following post on suffix trees as a pre-requisite for this post.Pattern Searching | Set 8 (Suffix Tree Introduction)A suffix array is a sorted array of all suffixes of a given string. The definition is similar to Suffix Tree which is compressed trie of all suffixes of t
15+ min read
Suffix Sum Array Suffix Sum ArrayGiven an array arr[] of size N, the task is to compute and return its suffix sum array. Suffix Sum is a precomputation technique in which the sum of all the elements of the original array from an index i till the end of the array is computed. Therefore, this suffix sum array will be
10 min read
Prefix Product Array Given an array arr[] of N integers the task is to generate a prefix product array from the given array. In a prefix product array, ith term pref[i] = arr[i] * arr[i - 1] * ...... * arr[0] Examples: Input: {1, 2, 3, 4, 5} Output: {1, 2, 6, 24, 120} Explanation: The Prefix Product Array will be {1, 2*
4 min read
Counting k-mers via Suffix Array Pre-requisite: Suffix Array. What are k-mers? The term k-mers typically refers to all the possible substrings of length k that are contained in a string. Counting all the k-mers in DNA/RNA sequencing reads is the preliminary step of many bioinformatics applications. What is a Suffix Array? A suffix
11 min read
C++ Program to Implement Suffix Array A suffix array is a data structure which can be used to store all possible suffixes of a given string in the sorted order. It stores the starting indices of the suffixes in lexicographical order. It is similar to trie data structure but is more space efficient then tries.ExampleLet the given string
3 min read
Suffix Array | Set 2 (nLogn Algorithm) Given a string, the task is to construct a suffix array for the given string. A suffix array is a sorted array of all suffixes of a given string. The definition is similar to Suffix Tree which is compressed trie of all suffixes of the given text. Examples: Input: str = "banana"Output: {5, 3, 1, 0, 4
15+ min read
Java Program to Implement Suffix Array A Suffix Array is a fundamental data structure used in string processing and computational biology. It represents an array of all suffixes of a given string, sorted lexicographically. Suffix arrays find applications in pattern matching, substring search, text compression, and bioinformatics, among o
3 min read
Array Data Structure Complete Guide to ArraysLearn more about Array in DSA Self Paced CoursePractice Problems on ArraysTop Quizzes on Arrays What is Array?An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calcul
3 min read
PL/SQL Arrays PL/SQL, an extension of SQL developed through Oracle, empowers builders with robust programming skills for powerful database management. Among its many capabilities, arrays stand out as an essential tool for organizing and manipulating data correctly. In this article, we'll dive deep into the secto
5 min read
Suffix Automation In computer science, a suffix automaton is an efficient data structure for representing the substring index of a given string which allows the storage, processing, and retrieval of compressed information about all its substrings. In this article, we will delve into the concept of suffix automation,
13 min read