0% found this document useful (0 votes)
6 views

Pattern Search Logic

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Pattern Search Logic

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Pattern Search Logic

By using simple for loop and indexing concept provide me a logic


Input 1 :
ABABDABACDABABCABAB
ABABCABAB
Output 1 :
Found pattern at index 10
Input 2:
ababcababcabcabc
abc
Output 2 :
Found pattern at index 2
Found pattern at index 7
Found pattern at index 10
Found pattern at index 13

To solve this using a simple for loop and indexing concept, we can use the sliding window technique to
iterate over the input string and compare substrings of the same length as the pattern. Here's the logic:

Steps:

1. Iterate through the input string, limiting the loop to `len(input_string) - len(pattern) + 1`
iterations to prevent out-of-bound errors.
2. In each iteration, extract a substring from the input string of the same length as the pattern.
3. Compare the substring with the pattern.
4. If they match, print the starting index of the match.

Here’s the Python code:

python

def find_pattern(input_string, pattern):


pattern_length = len(pattern)
input_length = len(input_string)

for i in range(input_length - pattern_length + 1):


# Extract substring of length equal to the pattern
if input_string[i:i + pattern_length] == pattern:
print(f"Found pattern at index {i}")

# Example Input/Output
# Test Case 1
input_string_1 = "ABABDABACDABABCABAB"
pattern_1 = "ABABCABAB"
find_pattern(input_string_1, pattern_1)

# Test Case 2
input_string_2 = "ababcababcabcabc"

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 1/13
pattern_2 = "abc"
find_pattern(input_string_2, pattern_2)

Output:

For Input 1:

perl

Found pattern at index 10

For Input 2:

perl

Found pattern at index 2


Found pattern at index 7
Found pattern at index 10
Found pattern at index 13

Problem Statement
You have been given three arrays A, B, and C in sorted format. By comparing all three arrays, pull
the least possible range.
Note: One element should be present mandatory from every array
Example:
Input:
arr1 = {3, 6, 8, 10, 15}
arr2 = {1, 5, 12}
arr3 = {4, 8, 15, 16}
Output: (3, 5)
Input format :
The input consists of three lists, a, b, and c, where each list contains a series of integers.
The rst line of input represents the length of list a.
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 11/42
The second set of lines represents the elements of a list a.
The third line represents the length of list b.
The fourth set of lines represents the elements of list b.
The fth line represents the length of list c, and the sixth set of lines represents the elements of list
c.
Output format :
The output is a pair of two integers representing the minimum range containing at least one
element from each of the three input lists.
Refer to the sample input and output for formatting specications.
Sample test cases :
Input 1 :
6
1
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 2/13
2
3
4
5
6
8
7
8
9
10
11
12
13
14
5
15
16
17
18
19
Output 1 :
(6, 15)
Input 2 :
5
3
6
8
10
15
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 12/42
3
1
5
12
4
4
8
15
16
Output 2 :
(3, 5)
To solve this problem, we can use a three-pointer approach to eciently nd the smallest range that
contains at least one element from each of the three sorted arrays. Here's the Python
implementation:
python
import sys
def find_min_range(arr1, arr2, arr3):
i, j, k = 0, 0, 0 # Pointers for arr1, arr2, and arr3
min_range = sys.maxsize
range_start, range_end = -1, -1
while i < len(arr1) and j < len(arr2) and k < len(arr3):
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 3/13
# Find the minimum and maximum elements among the current elements
min_val = min(arr1[i], arr2[j], arr3[k])
max_val = max(arr1[i], arr2[j], arr3[k])
# Update the minimum range if a smaller range is found
if max_val - min_val < min_range:
min_range = max_val - min_val
range_start, range_end = min_val, max_val
# Move the pointer of the array with the smallest value
if min_val == arr1[i]:
i += 1
elif min_val == arr2[j]:
j += 1
else:
k += 1
return (range_start, range_end)
# Sample input
print("Test Case 1:")
arr1 = [1, 2, 3, 4, 5, 6]
arr2 = [7, 8, 9, 10, 11, 12, 13, 14]
arr3 = [15, 16, 17, 18, 19]
print(find_min_range(arr1, arr2, arr3)) # Output: (6, 15)
print("\nTest Case 2:")
arr1 = [3, 6, 8, 10, 15]
arr2 = [1, 5, 12]
arr3 = [4, 8, 15, 16]
print(find_min_range(arr1, arr2, arr3)) # Output: (3, 5)

I need it in the simple format logic not complex

To provide a simple and clear logic, we can solve this problem using a three-pointer approach, as
follows:

Logic

1. Use three pointers (`i`, `j`, `k`) for the three arrays (`arr1`, `arr2`, `arr3`), starting at the
beginning of each array.
2. At every step:
Find the minimum value among the elements pointed to by `i`, `j`, and `k`.
Find the maximum value among these three elements.
Calculate the current range as `max_val - min_val`.
Keep track of the smallest range and its corresponding start and end values.
3. Increment the pointer of the array containing the minimum value, to try and include a larger
value from that array (since arrays are sorted).
4. Stop when any pointer reaches the end of its respective array.

Python Implementation

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

def find_min_range(arr1, arr2, arr3):


# Initialize pointers for the three arrays
i, j, k = 0, 0, 0
min_range = float('inf') # Start with an infinite range
range_start, range_end = -1, -1 # Initialize range values

# Loop until any pointer reaches the end of its array


while i < len(arr1) and j < len(arr2) and k < len(arr3):
# Find the minimum and maximum among the current elements
current_min = min(arr1[i], arr2[j], arr3[k])
current_max = max(arr1[i], arr2[j], arr3[k])

# Update the smallest range if a smaller range is found


if current_max - current_min < min_range:
min_range = current_max - current_min
range_start, range_end = current_min, current_max

# Move the pointer of the array with the smallest value


if current_min == arr1[i]:
i += 1
elif current_min == arr2[j]:
j += 1
else: # current_min == arr3[k]
k += 1

return (range_start, range_end)

# Example usage
print("Test Case 1:")
arr1 = [1, 2, 3, 4, 5, 6]
arr2 = [7, 8, 9, 10, 11, 12, 13, 14]
arr3 = [15, 16, 17, 18, 19]
print(find_min_range(arr1, arr2, arr3)) # Output: (6, 15)

print("\nTest Case 2:")


arr1 = [3, 6, 8, 10, 15]
arr2 = [1, 5, 12]
arr3 = [4, 8, 15, 16]
print(find_min_range(arr1, arr2, arr3)) # Output: (3, 5)

How it Works

1. Input: Three sorted arrays.


2. Pointers Movement:
Start by pointing to the first element of each array.
Always move the pointer of the array with the smallest value, aiming to minimize the range.
3. Output: The smallest range that contains at least one element from each array.

Output

Test Case 1:

scss

(6, 15)

Test Case 2:

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

(3, 5)

This approach is simple, readable, and efficient for the problem.

Problem Statement
You have been given three arrays A, B, and C in sorted format. By comparing all three arrays, pull
the least possible range.
Note: One element should be present mandatory from every array
Example:
Input:
arr1 = {3, 6, 8, 10, 15}
arr2 = {1, 5, 12}
arr3 = {4, 8, 15, 16}
Output: (3, 5)
Input format :
The input consists of three lists, a, b, and c, where each list contains a series of integers.
The rst line of input represents the length of list a.
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 11/42
The second set of lines represents the elements of a list a.
The third line represents the length of list b.
The fourth set of lines represents the elements of list b.
The fth line represents the length of list c, and the sixth set of lines represents the elements of list
c.
Output format :
The output is a pair of two integers representing the minimum range containing at least one
element from each of the three input lists.
Refer to the sample input and output for formatting specications.
Sample test cases :
Input 1 :
6
1
2
3
4
5
6
8
7
8
9
10
11
12
13
14

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 6/13
5
15
16
17
18
19
Output 1 :
(6, 15)
Input 2 :
5
3
6
8
10
15
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 12/42
3
1
5
12
4
4
8
15
16
Output 2 :
(3, 5)

Explain the question only.

Explanation of the Problem:

The problem is about finding the smallest range (a pair of two numbers) that contains at least one
number from each of the three given sorted arrays (A, B, and C).

Key Points to Understand:

1. Sorted Arrays:
You are given three arrays (A, B, and C), and they are already sorted in ascending order.
Each array can have a different number of elements.
2. Objective:
Identify a range `[x, y]` such that:
At least one number from each array falls within this range.
The difference `y - x` (the size of the range) is the smallest possible.
3. Mandatory Condition:
The range `[x, y]` must include:
At least one number from array A,
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 7/13
At least one number from array B, and
At least one number from array C.
4. Output:
The output is a pair of integers `(x, y)` that represents the smallest range.

Example Breakdown:

Input Example 1:

makefile

arr1 = {3, 6, 8, 10, 15}


arr2 = {1, 5, 12}
arr3 = {4, 8, 15, 16}

One possible range could be `[3, 15]` because:


`3` is from `arr1`.
`5` is from `arr2`.
`15` is from `arr3`.
However, `[3, 5]` is a better range because it is smaller, and:
`3` is from `arr1`.
`5` is from `arr2`.
`4` from `arr3` also fits within this range.

Output Example 1:

scss

(3, 5)

Input Example 2:

makefile

arr1 = {1, 2, 3, 4, 5, 6}
arr2 = {7, 8, 9, 10, 11, 12, 13, 14}
arr3 = {15, 16, 17, 18, 19}

The smallest range is `[6, 15]` because:


`6` is from `arr1`.
`7` is from `arr2`.
`15` is from `arr3`.

Output Example 2:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 8/13
scss

(6, 15)

Why is this Important?

The challenge is to balance the values from all three arrays while minimizing the range.
Since the arrays are sorted, the problem can be solved efficiently using a three-pointer approach
to focus on the smallest possible range.

min_range = float('inf') ?

`min_range = float('inf')` is a way to initialize the variable `min_range` with the largest possible value
in Python, representing infinity. This ensures that any range we calculate will be smaller than this initial
value, allowing us to find the minimum range effectively.

Why Use `float('inf')`?

1. Purpose:
To compare and update the range during the algorithm.
Since we are looking for the smallest range, we start with the largest possible value (infinity).
2. How it Works:
During the first calculation of a range (e.g., `max_val - min_val`), it will always be smaller than
`float('inf')`.
The value of `min_range` is then updated to this smaller range.
As the algorithm progresses, `min_range` will keep getting updated if a smaller range is
found.

Alternative Initializations

If you don't use `float('inf')`, you could initialize `min_range` with:

1. A large arbitrary value (e.g., `10**9` or `100000`), but this is less elegant and can fail for edge
cases involving very large inputs.
2. Use specific constraints if provided in the problem (e.g., the maximum possible difference).

Example Usage:

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

import sys

# Option 1: Using float('inf')


min_range = float('inf')

# Option 2: Using a large number


min_range = sys.maxsize # Maximum integer size in Python

# Option 3: Arbitrary large value


min_range = 1000000

Why `float('inf')` is Preferred:

1. It is clean and intuitive for representing "no finite minimum range found yet."
2. It works for any input size, including edge cases where the range is very large.

Permutation vs Combination python

Permutation vs Combination

Permutations and combinations are two fundamental concepts in combinatorics, often used to calculate
the number of ways to arrange or select items from a set.

Key Differences

Aspect Permutation Combination


Definition Order matters Order does not matter
n! n!
Formula P (n, r) = (n−r)!

C(n, r) = r!(n−r)!

Use Case Arranging items in a sequence Selecting items without regard to sequence

Example Permuting 3 items from 5 (ABC ≠ BCA) Choosing 3 items from 5 (ABC = BCA)

Python Code Examples

Python's `math` module provides built-in functions for permutations and combinations.

Permutations

The function `math.perm(n, r)` computes the number of permutations of n items taken r at a time.

python

import math

# Example: Permutations of 5 items taken 3 at a time

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 10/13
n = 5
r = 3
result = math.perm(n, r)
print(f"Number of permutations: {result}")

Output:

javascript

Number of permutations: 60

Combinations

The function `math.comb(n, r)` computes the number of combinations of n items taken r at a time.

python

import math

# Example: Combinations of 5 items taken 3 at a time


n = 5
r = 3
result = math.comb(n, r)
print(f"Number of combinations: {result}")

Output:

javascript

Number of combinations: 10

Manual Implementation

If you want to calculate permutations or combinations manually:

Permutations:

python

def permutations(n, r):


return math.factorial(n) // math.factorial(n - r)

# Example
n, r = 5, 3
print(f"Permutations: {permutations(n, r)}")

Combinations:

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

def combinations(n, r):


return math.factorial(n) // (math.factorial(r) * math.factorial(n - r))

# Example
n, r = 5, 3
print(f"Combinations: {combinations(n, r)}")

Comparison Example

python

import math

n, r = 5, 3

# Permutations
perm = math.perm(n, r)
print(f"Permutations (P({n}, {r})): {perm}")

# Combinations
comb = math.comb(n, r)
print(f"Combinations (C({n}, {r})): {comb}")

Output:

css

Permutations (P(5, 3)): 60


Combinations (C(5, 3)): 10

Conclusion

Use permutations when the order of items matters.


Use combinations when the order of items does not matter.

factorial using recursion

Here's a simple Python function to calculate the factorial of a number using recursion:

Factorial Using Recursion

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

def factorial(n):
# Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1:
return 1
# Recursive case
return n * factorial(n - 1)

# Example usage
number = 5
print(f"Factorial of {number} is {factorial(number)}")

How It Works

1. Base Case:
If n = 0 or n = 1, the factorial is 1.
This stops the recursion.
2. Recursive Case:
For n > 1, the function calls itself with n − 1, and multiplies the result by n.

Example Calculation (factorial(5))

1. factorial(5) = 5 × factorial(4)
2. factorial(4) = 4 × factorial(3)
3. factorial(3) = 3 × factorial(2)
4. factorial(2) = 2 × factorial(1)
5. factorial(1) = 1 (Base case)

Now, multiplying backward:

factorial(2) = 2 × 1 = 2
factorial(3) = 3 × 2 = 6
factorial(4) = 4 × 6 = 24
factorial(5) = 5 × 24 = 120

Output

csharp

Factorial of 5 is 120

This approach is intuitive but may not be efficient for very large values of n due to potential recursion
depth limits. For larger values, consider using an iterative approach or Python's `math.factorial`
function.

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

You might also like