Skip to content

Instantly share code, notes, and snippets.

@kienonline19
Created April 17, 2025 02:11
Show Gist options
  • Save kienonline19/edbd8de6cb26db58af8f44be0bb295dd to your computer and use it in GitHub Desktop.
Save kienonline19/edbd8de6cb26db58af8f44be0bb295dd to your computer and use it in GitHub Desktop.
5exercises

Python Backtracking Exercises: Subarray Problems

Exercise 1: List All Subarrays of a Given Array

Problem Statement: Write a function all_subarrays(arr) that uses backtracking to generate all possible subarrays (contiguous subsequences) of a given array.

Example:

Input: [1, 2, 3]
Output: [[], [1], [2], [3], [1, 2], [2, 3], [1, 2, 3]]

Exercise 2: Find All Subarrays with Sum Equal to Target

Problem Statement: Write a function subarrays_with_sum(arr, target) that uses backtracking to find all subarrays whose elements sum up to a given target value.

Example:

Input: arr = [1, 2, 3, 4, 5], target = 9
Output: [[2, 3, 4], [4, 5]]

Exercise 3: Find All Subarrays with Product Less Than K

Problem Statement: Write a function subarrays_with_product_less_than_k(arr, k) that uses backtracking to find all subarrays whose elements have a product less than k.

Example:

Input: arr = [10, 5, 2, 6], k = 100
Output: [[10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]]

Exercise 4: Find All Subarrays with Maximum Difference Less Than K

Problem Statement: Write a function subarrays_with_max_diff_less_than_k(arr, k) that uses backtracking to find all subarrays where the difference between the maximum and minimum elements is less than k.

Example:

Input: arr = [1, 3, 6, 10, 15], k = 5
Output: [[1], [3], [6], [10], [15], [1, 3], [3, 6], [6, 10], [10, 15]]

Exercise 5: Find All Subarrays with Equal Number of Odd and Even Elements

Problem Statement: Write a function subarrays_with_equal_odd_even(arr) that uses backtracking to find all subarrays having an equal number of odd and even elements.

Example:

Input: arr = [1, 2, 3, 4, 5]
Output: [[1, 2], [2, 3], [3, 4], [4, 5], [1, 2, 3, 4], [2, 3, 4, 5]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment