
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)
Editorial
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. |
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.