Search code examples
pythonlistuniquetraversal

To print out unique patterns from a list using Python


Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Notice that the solution set must not contain duplicate triplets.

Below is my code that finds the triplets. I couldn't find a solution to remove duplicate triplets pattern

Say if I/P is -1 0 1 0 the output must only be [[-1,0,1]] but what I get is [[1,-1,0],[0,-1,1]] ....any thoughts?

class Solution:
    def threeSum(self, nums):
        
        result = []
        
        for i in range (2, len(nums)):
            # i,j and k will be the pointers to the list
            k = i - 1
            j = i - 2
            for k in range (k, 0, -1):
                for j in range (j, -1, -1):

                    # verify if the summation is 0
                    if j < k and nums[i]+nums[j]+nums[k]== 0:
                        result.append([nums[i], nums[j], nums[k]])
    
        unique_list = []
        # logic to find unique list elements
        # this works only when the list patterns are same
        for x in result:
            if x not in unique_list:
                unique_list.append(x)
        
        return unique_list

Solution

  • you can do:

    for x in result:
        if sorted(x, key=int) not in unique_list:
            unique_list.append(sorted(x, key=int))
    
    return unique_list
    

    Like this all identical (but permuted) triplets are set with same sorting, so you won't get them twice.

    To answer user's comment:

    result = [[-1, 0, 1], [-1, 1, 0]]
    
    unique_list = []
    
    for x in result:
        if sorted(x, key=int) not in unique_list:
            unique_list.append(sorted(x, key=int))
    
    print (unique_list)
    
    result = [[1, -1, 0], [1, 0, -1]]
    
    unique_list = []
    
    for x in result:
        if sorted(x, key=int) not in unique_list:
            unique_list.append(sorted(x, key=int))
    
    print (unique_list)
    

    Output:

    [[-1, 0, 1]] #print 1
    [[-1, 0, 1]] #print 2