0% found this document useful (0 votes)
24 views24 pages

Input

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views24 pages

Input

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Problem Statement

You are given an integer array price, where price[i] is the price of the ith item in a shop.

There is a special discount for items in the shop.

If you buy the ith item, then you will receive a discount equivalent to price[j], where j is the
minimum index such that j > i and price[j] ≤ price[i].
Otherwise, you will not receive any discount at all.

Write a program to calculate the final prices for each item considering this special discount policy
using the insertion sort algorithm.

Example 1:

Input:

price = [8, 4, 6, 2, 3]

Output:

42423

Explanation:

For item 0 with price[0]=8, you will receive a discount equivalent to price[1]=4, therefore, the final
price you will pay is 8 - 4 = 4.

For item 1 with price[1]=4, you will receive a discount equivalent to price[3]=2, therefore, the final
price you will pay is 4 - 2 = 2.

For item 2 with price[2]=6, you will receive a discount equivalent to price[3]=2, therefore, the final
price you will pay is 6 - 2 = 4.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 1/24
For items 3 and 4, you will not receive any discount at all.

Example 2:

Input:

price = [1, 2, 3, 4, 5]

Output:

12345

Explanation:

In this case, for all items, you will not receive any discount at all.

Input format :
The first line of input consists of an integer N, denoting the number of items in the shop.

The second line consists of N space-separated integers, representing the prices of the items in the
shop.

Output format :
The output displays N space-separated integers, representing the final prices of the items after
applying the special discounts.

Refer to the sample output for the formatting specifications.

Code constraints :
1 ≤ N ≤ 500

1 ≤ prices of the item ≤ 1000

Sample test cases :


Input 1 :
5
84623
Output 1 :
42423
Input 2 :
5
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 2/24
12345
Output 2 :
12345

Here's the implementation of the problem using the insertion sort algorithm to calculate the final prices
based on the described discount policy:

Discount Prices

Explanation of the Code

1. Input Handling:
The first input is the number of items, `n`.
The second input is a space-separated list of integers representing the prices of items.
2. Discount Calculation:
For each item `i`, iterate through the prices of subsequent items `j` (where `j > i`) to find
the first eligible discount price (`price[j] <= price[i]`).
3. Final Price Update:
Deduct the identified discount from the original price and store it in the `final_prices` array.
4. Output:
Join and print the final prices as a space-separated string.

Sample Run

Input:

5
8 4 6 2 3

Output:

4 2 4 2 3

Input:

5
1 2 3 4 5

Output:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 3/24
1 2 3 4 5

n=int(input())
p=1
for i in range(1,n+1):
p=p*(2*i)*(2*i-1) // (i*(i+1))
print(p)

Explain the flow one by one

Let's break down the flow of the given Python code step by step:

Code:

python

n = int(input())
p = 1
for i in range(1, n + 1):
p = p * (2 * i) * (2 * i - 1) // (i * (i + 1))
print(p)

Step-by-Step Explanation:

1. Input:

python

n = int(input())

The user is prompted to input an integer `n`.


This integer represents how many iterations the loop will execute.
For example, if `n = 3`, the loop will run 3 times.

2. Initialization:

python

p = 1

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 4/24
A variable `p` is initialized with the value `1`.
This variable will hold the computed product at each iteration and store the final result.

3. For Loop:

python

for i in range(1, n + 1):

The loop starts with `i = 1` and increments by 1 in each iteration until it reaches `n`.
For example, if `n = 3`, the loop runs with `i = 1`, `i = 2`, and `i = 3`.

4. Inside the Loop:

python

p = p * (2 * i) * (2 * i - 1) // (i * (i + 1))

In each iteration, the value of `p` is updated using the formula:

(2i) × (2i − 1)
p=p×
i × (i + 1)

Let's break down the components:


(2i): Double the value of the current loop variable `i`.
(2i − 1): One less than double the value of `i`.
(i × (i + 1)): The product of `i` and the next integer (i + 1).
This calculation updates `p` in each step.

5. Example Calculation: Suppose n = 3:


Iteration 1 (i = 1):
(2 × 1) × (2 × 1 − 1) 2×1
p=1× =1× =1
1 × (1 + 1) 2
​ ​

Iteration 2 (i = 2):
(2 × 2) × (2 × 2 − 1) 4×3
p=1× =1× =2
2 × (2 + 1) 6
​ ​

Iteration 3 (i = 3):
(2 × 3) × (2 × 3 − 1) 6×5
p=2× =2× =5
3 × (3 + 1) 12
​ ​

Final Value of p: p = 5.

6. Output:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 5/24
python

print(p)

After the loop ends, the final value of `p` is printed.


For n = 3, the output is:

Key Observations:

The formula used in the loop calculates a product based on the series of factorial-like terms.
The double factorial terms (2i) and (2i − 1) are divided by a combination of i and (i + 1),
reducing the growth of the product.

n = int(input())
l = list(map(int, input().split()))
print(*l)
c=0
for i in range(1,n):
if(l[i]<l[i-1]):
if c==1:
print("false")
break
c=c+1
if i == 1 or l[i-2] <= l[i]:
l[i-1] = l[i]
else:
l[i] = l[i-1]

else:
print("true")
Input :
3
432
output:
432
true

explain the flo

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 6/24
Let's break down the flow of the provided Python code step by step:

Code:

python

n = int(input())
l = list(map(int, input().split()))
print(*l)
c = 0
for i in range(1, n):
if l[i] < l[i-1]:
if c == 1:
print("false")
break
c = c + 1
if i == 1 or l[i-2] <= l[i]:
l[i-1] = l[i]
else:
l[i] = l[i-1]
else:
print("true")

Step-by-Step Explanation:

1. Input:

python

n = int(input())
l = list(map(int, input().split()))
print(*l)

`n`:
The user inputs the size of the list `n`.
`l`:
The user inputs a space-separated list of integers. It is stored as a list `l` of length `n`.
The `print(*l)` statement prints the input list elements separated by a space.
Example Input:

3
4 3 2

Output of `print(*l)`:

4 3 2

2. Initialization:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 7/24
python

c = 0

A counter `c` is initialized to `0`. It tracks the number of times an element in the list needs to
be adjusted to satisfy a specific condition (explained below).

3. For Loop:

python

for i in range(1, n):

The loop iterates over the indices of the list from `1` to `n-1` (inclusive). This ensures we
always compare `l[i]` with its previous element `l[i-1]`.

4. Condition Check:

python

if l[i] < l[i-1]:

If the current element `l[i]` is smaller than the previous element `l[i-1]`, a violation is
detected (since the list is expected to be non-decreasing).

5. Violation Handling:

python

if c == 1:
print("false")
break

If a violation has already been fixed once (`c == 1`), the program concludes that it's not
possible to fix the list by modifying at most one element and prints `"false"`. The program
then exits the loop.

6. Adjusting the List:

python

c = c + 1
if i == 1 or l[i-2] <= l[i]:
l[i-1] = l[i]

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 8/24
else:
l[i] = l[i-1]

The counter `c` is incremented to mark that a violation has been handled.
Two Cases for Adjustment:
1. Case 1: If `i == 1` (first comparison) or `l[i-2] <= l[i]` (the second-to-last element is
less than or equal to the current element):
Modify `l[i-1]` (the previous element) to match the current element `l[i]`.
2. Case 2: Otherwise:
Modify `l[i]` (the current element) to match the previous element `l[i-1]`.

7. Loop Completion:

python

else:
print("true")

If the loop completes without breaking (no more than one violation is detected), the program
prints `"true"`, indicating that the list can be adjusted to become non-decreasing by
modifying at most one element.

Example Walkthrough:

Input:

3
4 3 2

Execution:

Initialization:
`n = 3`
`l = [4, 3, 2]`
`print(*l)` → Output: `4 3 2`
Iteration 1 (`i = 1`):
`l[1] = 3`, `l[0] = 4`
`3 < 4` → Violation detected.
`c = 0` → First violation, adjust list:
`i == 1` → Modify `l[0] = l[1]`
`l = [3, 3, 2]`
`c = 1`
Iteration 2 (`i = 2`):
`l[2] = 2`, `l[1] = 3`
`2 < 3` → Violation detected.
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 9/24
`c = 1` → Second violation, print `"false"` and break.

Output:

arduino

4 3 2
false

Key Insights:

The program tries to make the list non-decreasing by modifying at most one element.
If more than one modification is needed, it outputs `"false"`.
If successful, it outputs `"true"`.

Problem Statement

Given an integer n, return all the strobogrammatic numbers that are of length n.

A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at
upside down).

Examples

Input: n = 2

Output: 11 88 69 96

Input: n = 1

Output: 0 1 8

Input format :
The input consists of an integer n.

Output format :

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 10/24
The output prints the integers, representing all the strobogrammatic numbers that are of length n,
separated by a space.

Refer to the sample output for formatting specifications.

Code constraints :
1≤n≤8

Sample test cases :


Input 1 :
1
Output 1 :
018
Input 2 :
2
Output 2 :
11 88 69 96

The code has been updated to implement the generation of strobogrammatic numbers of length `n`.
Here's a brief explanation of the logic:

1. Recursive Functionality:
A helper function `build_strobogrammatic` builds strobogrammatic numbers using valid digit
pairs.
2. Base Handling for `n = 1`:
Special case for single-digit strobogrammatic numbers: `0`, `1`, and `8`.
3. Valid Pairs:
`00`, `11`, `69`, `88`, and `96` are used to construct strobogrammatic numbers.
4. Skipping Leading Zeros:
When constructing numbers, pairs starting with `0` are avoided for the outermost digits.
5. Output:
The resulting numbers are printed space-separated as per the requirement.

Try running the updated code with different values of `n`!

Problem Statement

Given two strings s and t of lengths m and n respectively, return the minimum window substring of
s such that every character in t (including duplicates) is included in the window. If there is no such
substring, return an empty string.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 11/24
Examples

Input: s = ADOBECODEBANC, t = ABC

Output: BANC

Explanation: The minimum window substring BANC includes 'A', 'B', and 'C' from string t.

Input: s = a, t = a

Output: a

Explanation: The entire string s is the minimum window.

Input: s = a, t = aa

Output:

Explanation: Both 'a's from t must be included in the window. Since the largest window of s only has
one 'a', return an empty string.

The code has been updated to solve the "minimum window substring" problem using the sliding
window technique. Here's a summary of the approach:

1. Data Structures:
A `Counter` is used to keep track of the characters in `t` and their counts.
A `window_count` counter tracks characters within the current sliding window in `s`.
2. Sliding Window Technique:
Expand the window by moving the right pointer (`r`) and include the character in the
`window_count`.
When the current window satisfies the condition (all characters from `t` are included with the
required frequency), contract the window from the left pointer (`l`) to find the smallest valid
window.
3. Tracking Result:
Keep track of the smallest valid window's start and end indices, updating them whenever a
smaller valid window is found.
4. Output:
If a valid window is found, the substring is returned; otherwise, an empty string is returned.
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 12/24
Try testing the updated code with different input values!

Given an integer n, return all the strobogrammatic numbers that are of length n.

A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at
upside down).

Examples

Input: n = 2

Output: 11 88 69 96

Input: n = 1

Output: 0 1 8

Input format :
The input consists of an integer n.

Output format :
The output prints the integers, representing all the strobogrammatic numbers that are of length n,
separated by a space.

Refer to the sample output for formatting specifications.

Code constraints :
1≤n≤8

Sample test cases :


Input 1 :
1
Output 1 :
018
Input 2 :
2
Output 2 :
11 88 69 96

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 13/24
The code has been updated to generate all strobogrammatic numbers of length `n`. It uses a recursive
helper function to build the numbers by appending valid pairs. Here's how it works:

1. Valid Digit Pairs:


Digits that form strobogrammatic numbers when paired: `(0,0)`, `(1,1)`, `(8,8)`, `(6,9)`,
and `(9,6)`.
2. Recursive Building:
Start with valid pairs, and recursively build numbers until the desired length `n` is achieved.
3. Special Cases:
For single-digit numbers (`n = 1`), the valid strobogrammatic numbers are `0`, `1`, and `8`.
4. Output:
The strobogrammatic numbers are joined with spaces and printed as required.

You can now test the code with any input value of `n`!

We can rotate digits by 180 degrees to form new digits. When 0, 1, 6, 8, 9 are rotated 180 degrees,
they become 0, 1, 9, 8, 6 respectively. When 2, 3, 4, 5 and 7 are rotated 180 degrees, they become
invalid.

A confusing number is a number that when rotated 180 degrees becomes a different number with
each digit valid. (Note that the rotated number can be greater than the original number)

Given a positive integer N, return the number of confusing numbers between 1 and N inclusive.

Example

Input: 16

Output: 4

Explanation:

The confusing numbers are {6, 9, 10, 16}.

6 converts to 9.

9 converts to 6.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 14/24
10 converts to 01 which is just 1.

16 converts to 91.

Input format :
The input consists of a positive integer N.

Output format :
The output prints an integer, representing the number of confusing numbers between 1 and N
inclusive.

Refer to the sample output for formatting specifications.

Code constraints :
1 ≤ N ≤ 103

Sample test cases :


Input 1 :
16
Output 1 :
4
Input 2 :
69
Output 2 :
10
Input 3 :
20
Output 3 :
6

I need a simple logic not complex

The code has been simplified to determine the count of confusing numbers up to a given `N`. Here's a
breakdown of the logic:

1. Digit Mapping:
A dictionary maps valid digits (`0, 1, 6, 8, 9`) to their rotated counterparts (`0, 1, 9, 8,
6`).
2. Confusing Number Check:
A number is confusing if its rotated form (constructed by reversing the digits and replacing
them using the map) differs from the original.
3. Iteration:
The code iterates through all numbers from `1` to `N` and checks if each is confusing.
4. Output:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 15/24
The total count of confusing numbers is printed.

This approach is straightforward and handles the requirements efficiently for `N` up to `103`.

more simple concepts using loop and list

Discount Prices
def count_confusing_numbers(n):
# List of valid digits and their rotated counterparts
rotation_map = {0: 0, 1: 1, 6: 9, 8: 8, 9: 6}

count = 0

for num in range(1, n + 1):


original = num
rotated = 0

while num > 0:


digit = num % 10
if digit not in rotation_map:
break
rotated = rotated * 10 + rotation_map[digit]
num //= 10
else: # Executes if no `break` occurred
if rotated != original:
count += 1
The code has been updated to simplify the logic using loops and basic lists. Here's how it works now:
return count
1. Rotation Mapping:
# Input
A dictionary amaps
n = int(input("Enter digitsinteger
positive to theirN:
rotated
")) counterparts (`0 ↔ 0, 1 ↔ 1, 6 ↔ 9, 8 ↔ 8, 9 ↔ 6`).
2. Number Rotation:
# Count confusing numbers
Each number is broken into
result = count_confusing_numbers(n) digits, rotated using the map, and rebuilt in reverse order.
3. Validation:
# Output
A number
print(result) is considered confusing if its rotated form does not equal the original number.
4. Loop:
A single loop iterates through numbers from `1` to `N`, counting how many are confusing.

This is a clean and efficient solution while remaining easy to follow.

def count_confusing_numbers(n):
rotation_map = {0: 0, 1: 1, 6: 9, 8: 8, 9: 6}
count = 0
for num in range(1, n + 1):
original = num
rotated = 0
while num > 0:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 16/24
digit = num % 10
if digit not in rotation_map:
break
rotated = rotated * 10 + rotation_map[digit]
num //= 10
else:
if rotated != original:
count += 1
return count

n = int(input())
# n=16

result = count_confusing_numbers(n)

print(result)

provide this code in the copying format

Here is your code in a copying-friendly format:

python

def count_confusing_numbers(n):
rotation_map = {0: 0, 1: 1, 6: 9, 8: 8, 9: 6}
count = 0
for num in range(1, n + 1):
original = num
rotated = 0
while num > 0:
digit = num % 10
if digit not in rotation_map:
break
rotated = rotated * 10 + rotation_map[digit]
num //= 10
else:
if rotated != original:
count += 1
return count

n = int(input())
# n=16

result = count_confusing_numbers(n)

print(result)

Strobogrammatic Numbers

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 17/24
I’ve added a simple Python implementation to generate strobogrammatic numbers of length `n`. The
approach builds numbers recursively while ensuring leading zeros are avoided for valid cases. Let me
know if you need further explanations or edits!

Single File Programming Question


Problem Statement

Given an integer n, return all the strobogrammatic numbers that are of length n.

A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at
upside down).

Examples

Input: n = 2

Output: 11 88 69 96

Input: n = 1

Output: 0 1 8

Input format :
The input consists of an integer n.

Output format :
The output prints the integers, representing all the strobogrammatic numbers that are of length n,
separated by a space.

Refer to the sample output for formatting specifications.

Code constraints :
1≤n≤8

Sample test cases :


Input 1 :

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 18/24
1
Output 1 :
018
Input 2 :
2
Output 2 :
11 88 69 96

in simple way

I've added a simple implementation for generating strobogrammatic numbers of length `n`. It uses
recursion and avoids leading zeros for valid cases. Let me know if there's anything more you'd like to
adjust!

Single File Programming Question


Problem Statement

Given an integer n, return all the strobogrammatic numbers that are of length n.

A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at
upside down).

Examples

Input: n = 2

Output: 11 88 69 96

Input: n = 1

Output: 0 1 8

Input format :
The input consists of an integer n.

Output format :

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 19/24
The output prints the integers, representing all the strobogrammatic numbers that are of length n,
separated by a space.

Refer to the sample output for formatting specifications.

Code constraints :
1≤n≤8

Sample test cases :


Input 1 :
1
Output 1 :
018
Input 2 :
2
Output 2 :
11 88 69 96

Python code in simple way

Here's a simple Python implementation to generate all strobogrammatic numbers of length `n`:

python

def find_strobogrammatic(n):
# Helper function to recursively build strobogrammatic numbers
def build_strobogrammatic(length, total_length):
if length == 0:
return [""]
if length == 1:
return ["0", "1", "8"]

smaller_numbers = build_strobogrammatic(length - 2, total_length)


result = []
pairs = [("0", "0"), ("1", "1"), ("6", "9"), ("8", "8"), ("9", "6")]

for num in smaller_numbers:


for a, b in pairs:
if length != total_length or a != "0": # Avoid leading zeros
result.append(a + num + b)

return result

return build_strobogrammatic(n, n)

# Input
n = int(input("Enter the value of n: "))

# Generate and print strobogrammatic numbers


strobogrammatic_numbers = find_strobogrammatic(n)
print(" ".join(strobogrammatic_numbers))

How It Works:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 20/24
1. Base Cases:
When `length == 0`, return an empty string (used for even lengths).
When `length == 1`, return `["0", "1", "8"]` (used for odd lengths).
2. Recursive Construction:
Build smaller strobogrammatic numbers for `length - 2`.
Add strobogrammatic digit pairs around the smaller numbers.
3. Avoid Leading Zeros:
For outermost digits (`length == total_length`), skip the pair `("0", "0")`.

Example:

Input: `n = 2`
Output: `11 88 69 96`

This approach is efficient and concise while adhering to the constraints.

def find_strobogrammatic(n):
# Helper function to recursively build strobogrammatic numbers
def build_strobogrammatic(length, total_length):
if length == 0:
return [""]
if length == 1:
return ["0", "1", "8"]

smaller_numbers = build_strobogrammatic(length - 2, total_length)


result = []
pairs = [("0", "0"), ("1", "1"), ("6", "9"), ("8", "8"), ("9", "6")]

for num in smaller_numbers:


for a, b in pairs:
if length != total_length or a != "0": # Avoid leading zeros
result.append(a + num + b)

return result

return build_strobogrammatic(n, n)

# Input
n = int(input("Enter the value of n: "))

# Generate and print strobogrammatic numbers


strobogrammatic_numbers = find_strobogrammatic(n)
print(" ".join(strobogrammatic_numbers))

using recursion in simple way

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 21/24
Strobogrammatic Numbers

def find_strobogrammatic(n): # Helper function to recursively build strobogrammatic numbers def


build_strobogrammatic(length): if length == 0: return [""] if length == 1: return ["0", "1", "8"]
smaller_numbers = build_strobogrammatic(length - 2)
result = []
pairs = [("0", "0"), ("1", "1"), ("6", "9"), ("8", "8"), ("9", "6")]

for num in smaller_numbers:


for a, b in pairs:
if length != n or a != "0": # Avoid leading zeros
result.append(a + num + b)

return result

return build_strobogrammatic(n)

Input
The code has been updated to simplify the recursive structure. Let me know if further adjustments are
n = int(input("Enter the value of n: "))
needed!

Generate and print strobogrammatic numbers

strobogrammatic_numbers = find_strobogrammatic(n) print(" ".join(strobogrammatic_numbers))


We are given two strings, s (the source string) and t (the target string), and we need to find the
smallest window in s that contains all characters in t, including duplicates. If no such window exists,
return an empty string.

Example:
Input:
s = "ADOBECODEBANC"
t = "ABC"
Output:
"BANC"
The minimum window in s that contains all characters in t is "BANC".

I need to solve this qsn through for loop and combination simply.

Here's a simple approach to solve the minimum window substring problem using for-loops and a
straightforward sliding window technique:

python

def min_window(s, t):


from collections import Counter

# Count frequency of characters in t


target_count = Counter(t)
required = len(target_count) # Number of unique characters to match
window_count = {}

left = 0
formed = 0

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 22/24
min_length = float("inf")
result = ""

# Loop through s with a sliding window


for right in range(len(s)):
char = s[right]
window_count[char] = window_count.get(char, 0) + 1

# Check if current character satisfies the target condition


if char in target_count and window_count[char] == target_count[char]:
formed += 1

# Shrink the window if all characters are matched


while formed == required:
# Update the result if a smaller window is found
if right - left + 1 < min_length:
min_length = right - left + 1
result = s[left:right + 1]

# Remove leftmost character from the window


window_count[s[left]] -= 1
if s[left] in target_count and window_count[s[left]] < target_count[s[left]]:
formed -= 1
left += 1

return result

# Input
s = "ADOBECODEBANC"
t = "ABC"

# Output
print(min_window(s, t))

Explanation:

1. Character Frequency:
Use a `Counter` to store the frequency of characters in `t`.
2. Sliding Window:
Use two pointers (`left` and `right`) to represent a window in `s`.
Expand the `right` pointer to include characters in the window.
Shrink the `left` pointer when all characters in `t` are satisfied within the current window.
3. Check Window Validity:
Maintain a count (`formed`) to track how many unique characters in `t` are fully matched in
the current window.
4. Update Result:
Whenever the window satisfies the condition (all characters in `t` are matched), update the
result if the window size is smaller than the previously found window.
5. Efficiency:
This approach ensures each character is processed at most twice (once when added and once
when removed), leading to a time complexity of O(n + m), where n is the length of `s` and
m is the length of `t`.

Example Walkthrough:

For `s = "ADOBECODEBANC"` and `t = "ABC"`, the sliding window:

Expands to include characters until all characters in `t` are matched.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 23/24
Shrinks to remove unnecessary characters while still satisfying the condition.
Finds the minimum window `"BANC"`.

code for finding all possible substring in the string

Here's a Python program to generate all possible substrings of a given string:

python

def find_all_substrings(s):
substrings = []
n = len(s)
for i in range(n):
for j in range(i + 1, n + 1): # j goes from i+1 to n to include the substring endin
g at j
substrings.append(s[i:j])
return substrings

# Input
string = input("Enter a string: ")

# Generate and print all substrings


result = find_all_substrings(string)
print("All possible substrings:")
print(result)

How It Works:

1. Nested Loops:
Outer loop (`i`) iterates over the starting index of the substring.
Inner loop (`j`) iterates from `i + 1` to the end of the string to determine the ending index
of the substring.
2. Substring Extraction:
Use slicing (`s[i:j]`) to extract each substring between indices `i` and `j`.

Example:

Input: `abc`
Output:

less

All possible substrings:


['a', 'ab', 'abc', 'b', 'bc', 'c']

This approach is simple and ensures that all substrings are included.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 24/24

You might also like