0

I am trying to write the sublist search algorithm using Python.

For reference : https://www.geeksforgeeks.org/sublist-search-search-a-linked-list-in-another-list/

Here is my code:

def sublist(arr1,arr2):
i = 0
j = 0
k = 0
if len(arr1) == 0:
    print('List1 Empty')
if len(arr2) == 0:
    print('List 2 Empty')
for j in range(0,len(arr2)):
    for i in range(0,len(arr1)):
        if arr1[i] != arr2[j]:
            break
        while arr1[i] == arr2 [j]:
            if i == len(arr1) - 1:
                return True
            i = i + 1
            j = j + 1
            if i == len(arr1):
                return False
        return False 

I am sure this code can be optimized and reduce time complexity. Because of while loop, does the complexity increase than O(m*n)? Beginner student here

  • 1
    Are you sure this code works? Seems like you don't need the second for loop if you just make `i = 0` before each iteration. – Yonlif Mar 06 '19 at 19:01
  • @Yonlif You're right. The second for loop never actually needs to iterate since it traverses the supposed sublist so if the first index does not match there is no need to traverse the list further and it won't due to the first `if` having a `break` statement. All other code paths return so the loop will never be executed more than once. Essentially the `for` loop is just fancy way of resetting `i = 0`. – MrDeal Mar 06 '19 at 19:25

2 Answers2

1

I think that this works better:

def sublist(arr1,arr2):
  "This fuction checks if arr1 is a sublist of arr2."
  for i in range(len(arr2)):
    part=arr2[i:] # part is a list which all the elements from i to the end of arr2
    if len(part)<len(arr1):
      return False
    if arr1==part[:len(arr1)]: # if arr1 is in the beginning of part return True
      return True
  return False
t3m2
  • 366
  • 1
  • 15
  • Yes this works but you could save space by not using `part` and instead just performing the operations on `arr2` using `i`. – MrDeal Mar 06 '19 at 19:52
  • You do not need to specify both limits of a slice. `part=arr2[i:]` and `elif arr1 == part[:len(arr1)]` would suffice. – Dillon Davis Mar 06 '19 at 22:39
  • @MrDeal Using `part` saves time: [https://stackoverflow.com/questions/55542474/should-i-store-a-calculation-in-a-variable-if-it-will-be-used-a-lot](https://stackoverflow.com/questions/55542474/should-i-store-a-calculation-in-a-variable-if-it-will-be-used-a-lot) – t3m2 Apr 06 '19 at 13:08
1

The following compares the first portion of arr2 to arr1, to determine if they are equal. If so, or any recursive call on some offset of arr2 returns true, then return true. Otherwise, if at any point the sublist of the original arr2 is shorter than arr1, return False.

def sublist(arr1, arr2):
    if len(arr2) < len(arr1):
        return False
    return arr1 == arr2[:len(arr1)] or sublist(arr1, arr2[1:])
Dillon Davis
  • 6,679
  • 2
  • 15
  • 37