Tutorialspoint
Problem
Solution
Submissions

Check if a List Contains a Sublist

Certification: Intermediate Level Accuracy: 38.24% Submissions: 34 Points: 10

Write a Python function to check if a given list contains another list as a sublist.

Example 1
  • Input: main_list = [1, 2, 3, 4, 5], sublist = [2, 3]
  • Output: True
  • Explanation:
    • Step 1: Check if [2, 3] exists as a contiguous subsequence in [1, 2, 3, 4, 5].
    • Step 2: Start comparing from index 0 of main_list: [1, 2, 3, 4, 5]. No match at position 0.
    • Step 3: Try from index 1: [1, 2, 3, 4, 5]. Found match: 2 matches 2.
    • Step 4: Check next element: 3 matches 3.
    • Step 5: All elements in sublist are found in sequence, so return True.
Example 2
  • Input: main_list = [1, 2, 3, 4, 5], sublist = [3, 5]
  • Output: False
  • Explanation:
    • Step 1: Check if [3, 5] exists as a contiguous subsequence in [1, 2, 3, 4, 5].
    • Step 2: Start comparing from index 0 of main_list: [1, 2, 3, 4, 5]. No match at position 0.
    • Step 3: Try from index 1: [1, 2, 3, 4, 5]. No match at position 1.
    • Step 4: Try from index 2: [1, 2, 3, 4, 5]. Found match: 3 matches 3.
    • Step 5: Check next element: 4 does not match 5.
    • Step 6: No continuous sequence found matching the sublist, so return False.
Constraints
  • 1 <= len(main_list), len(sublist) <= 1000
  • Time Complexity: O(n * m) where n is the length of the main list and m is the length of the sublist
  • Space Complexity: O(1)
Control StructuresListGoogleTCS (Tata Consultancy Services)
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use nested loops to check if the sublist exists in the main list.
  • Handle edge cases where the sublist is empty or longer than the main list.

Steps to solve by this approach:

 Step 1: Handle edge cases - empty sublist is always contained in any list
 
 Step 2: Check if sublist is longer than main_list (impossible to contain)
 Step 3: Iterate through main_list up to the position where sublist can still fit
 Step 4: At each position i, check if the slice main_list[i:i+len(sublist)] equals sublist
 Step 5: If a match is found, return True
 Step 6: If no match is found after complete iteration, return False
 Step 7: Return the result, indicating whether sublist exists within main_list

Submitted Code :