Prepin
Log in

Display all sub-arrays of an array that contain unique elements.

Approach / Explanation

This question requires you to create a function that accepts an array as input and prints all subsets (or "sub-arrays") of the original array that contain distinct elements, meaning there are no repetitions. This is a basic question related to array and set operations, likely aimed at assessing your skills in array manipulation and understanding of algorithm complexity. To effectively address this question, there are several considerations to keep in mind. First, you should grasp the concept of a "sub-array," which is a subset of the original array that preserves the order of its elements. Second, you need to be able to determine whether all elements in a subset are distinct. A useful method for this is to utilize a Set data structure, as it inherently disallows duplicate entries, ensuring that the elements are unique. Lastly, you must devise a way to generate all possible sub-arrays from the provided array.

Suggested Answer

Here is a Python example: def print_sub_arrays ( arr ) : n = len ( arr ) for i in range ( n ) : distinct_set = set ( ) for j in range ( i , n ) : if arr [ j ] in distinct_set : break else : distinct_set . add ( arr [ j ] ) print ( arr [ i : j + 1 ] ) array = [ 1 , 2 , 3 , 4 ] print_sub_arrays ( array ) In this example, we first set up a nested loop to generate all possible subarrays. We then initialize a set called distinct_set to keep track of unique elements. If we encounter an element that is already in distinct_set , we exit the loop, indicating that the subarray contains duplicate elements. If the element is not present, we add it to the set and print the subarray.

Alternative Answer

Below is an example of a comparable function written in Java: import java . util . HashSet ; public void printDistinctSubarrays ( int [ ] arr ) { int n = arr . length ; for ( int i = 0 ; i < n ; i ++ ) { HashSet < Integer > set = new HashSet < > ( ) ; for ( int j = i ; j < n ; j ++ ) { if ( set . contains ( arr [ j ] ) ) break ; else set . add ( arr [ j ] ) ; for ( int k = i ; k <= j ; k ++ ) System . out . print ( arr [ k ] + " " ) ; System . out . println ( ) ; } } } Like the Python example, this Java function employs a nested loop to create all possible sub-arrays. The elements from these sub-arrays are added to a HashSet to ensure all elements are unique. If an element is already present in the set, it indicates a duplicate, and the loop is terminated. If not, the element is added to the set, and the sub-array is printed.

Question Details

Difficulty & Category

Medium

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.