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

Remove Duplicate Characters

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

Remove Duplicate Characters

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

Remove Duplicate Characters

You have been given a string having space-separated multiple words. Reprint the string after
removing the characters that occur more than once in the string. You are supposed to remove the
later occurrences of a character.
testcase:
Input 2 :
quick fox jumps lake
Output 2 :
quick foxjmpslaein python

To achieve the desired result, you can write a Python function to process the string. Below is the
implementation:

python

def remove_duplicate_characters(s):
seen = set()
result = []
for char in s:
if char not in seen:
result.append(char)
seen.add(char)
return ''.join(result)

# Test case
input_2 = "quick fox jumps lake"
output_2 = remove_duplicate_characters(input_2)
print(output_2)

Explanation:

1. Input: The string is traversed character by character.


2. Set: A set is used to keep track of characters that have been added to the result.
3. Result: Characters that have not been seen before are appended to the result list and added to the
set.
4. Output: The final string is joined from the list.

Output for the Test Case:

For the input `"quick fox jumps lake"`, the output will be:

quick foxjmpslae

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 1/42
Problem Statement

Given an array A of size N that contains only non-negative integers, find a continuous sub-array that
adds to a given number S and return the left and right indexes of that sub-array. In the case of
multiple subarrays, return the subarray indexes that come first when moving from left to right.

Note: Both the indexes in the array should be according to 1-based indexing. You have to return an
array list consisting of two elements, left and right. If no such subarray exists, return an array
consisting of element -1.

Example 1

Input:

N = 5, S = 12

A[5] = {1,2,3,7,5}

Output:

24

Explanation:

The sum of elements from the 2nd position to the 4th position is 12.

Example 2

Input:

N = 10, S = 15

A[10] = {1,2,3,4,5,6,7,8,9,10}

Output:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 2/42
15

Explanation:

The sum of elements from the 1st position to the 5th position is 15.

Sample test cases :


Input 1 :
5
12
12375
Output 1 :
24
Input 2 :
10
15
1 2 3 4 5 6 7 8 9 10
Output 2 :
15
Input 3 :
3
22
145
Output 3 :
-1

Here is the Python code to solve the problem. It uses a sliding window (or two-pointer) approach to
efficiently find the continuous sub-array that adds up to the given sum S .

python

def find_subarray_with_sum(n, s, arr):


left = 0
current_sum = 0

for right in range(n):


# Add the current element to the window's sum
current_sum += arr[right]

# Shrink the window from the left if the sum exceeds the target
while current_sum > s and left <= right:
current_sum -= arr[left]
left += 1

# Check if the current sum matches the target


if current_sum == s:
# Return 1-based indices
return [left + 1, right + 1]

# If no such sub-array is found, return [-1]


return [-1]

# Test cases
print(find_subarray_with_sum(5, 12, [1, 2, 3, 7, 5])) # Output: [2, 4]

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 3/42
print(find_subarray_with_sum(10, 15, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])) # Output: [1, 5]
print(find_subarray_with_sum(3, 22, [1, 4, 5])) # Output: [-1]

Explanation:

1. Sliding Window Approach:


The `right` pointer expands the window by adding the current element to `current_sum`.
If `current_sum` exceeds the target S , the `left` pointer shrinks the window from the left.
This ensures we maintain a continuous subarray with a sum equal to or less than S .
2. 1-Based Indexing:
The indices are adjusted to match 1-based indexing by adding 1 to `left` and `right`.
3. Output:
If a subarray with the sum S is found, return its start and end indices.
If no such subarray exists, return `[-1]`.

Complexity:

Time Complexity: O(N ), as each element is processed at most twice (once by `right` and at most
once by `left`).
Space Complexity: O(1), as no additional space is used apart from variables.

Problem Statement:

Suppose you have been keeping an eye on the stock market for a while, and you have been tracking
the daily prices of a particular stock. You want to make a profit by buying and selling the stock at the
right time.

Given the array of prices of the stock on each day, you need to figure out the best strategy to
maximize your profit.

However, if the stock prices are constantly decreasing, there is no way for you to make a profit.

Example 1:

Input:

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

arr[] = {100, 180, 260, 310, 40, 535, 695}

Output:

865

Explanation:

Buy the stock on day 0 and sell it on day 3 => 310 – 100 = 210

Buy the stock on day 4 and sell it on day 6 => 695 – 40 = 655

Maximum Profit = 210 + 655 = 865

Example 2:

Input:

arr[] = {4, 2, 2, 2, 4}

Output:

Explanation:

Buy the stock on day 1 and sell it on day 4 => 4 – 2 = 2

Maximum Profit = 2

Note: This question was asked by Facebook in their written exam.


Sample test cases :
Input 1 :
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 5/42
7
100 180 260 310 40 535 695
Output 1 :
865
Input 2 :
5
42224
Output 2 :
2
Input 3 :
5
10 8 6 4 2
Output 3 :
0
Input 4 :
5
13579
Output 4 :
8

Here is the Python solution to maximize the profit by identifying the optimal buy-and-sell days for the
given stock prices:

python

def max_profit(prices):
n = len(prices)
if n < 2:
return 0

max_profit = 0

for i in range(1, n):


# If there is a profit opportunity (price is increasing)
if prices[i] > prices[i - 1]:
max_profit += prices[i] - prices[i - 1]

return max_profit

# Test cases
print(max_profit([100, 180, 260, 310, 40, 535, 695])) # Output: 865
print(max_profit([4, 2, 2, 2, 4])) # Output: 2
print(max_profit([10, 8, 6, 4, 2])) # Output: 0
print(max_profit([1, 3, 5, 7, 9])) # Output: 8

Explanation:

1. Core Idea:
The problem can be reduced to identifying all upward trends in the price sequence.
For every increase prices[i] > prices[i-1], you can consider buying at prices[i-1] and selling
at prices[i].
2. Algorithm:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 6/42
Loop through the array from the second element.
For each day, if the price is higher than the previous day, add the difference to the profit.
3. Edge Cases:
If the prices are constantly decreasing, no profit can be made.
If the prices are constantly increasing, sum up all daily differences.
4. Complexity:
Time Complexity: O(N ), where N is the number of days.
Space Complexity: O(1), as we use only a constant amount of extra space.

Output for Sample Test Cases:

Input: `[100, 180, 260, 310, 40, 535, 695]`


Output: `865`
Input: `[4, 2, 2, 2, 4]`
Output: `2`
Input: `[10, 8, 6, 4, 2]`
Output: `0`
Input: `[1, 3, 5, 7, 9]`
Output: `8`

KMP Algorithm for Pattern Searching

Raj is working on a project that involves searching for a specific pattern in a given text. He has heard
about the Knuth-Morris-Pratt (KMP) algorithm, which is efficient for string matching, and he decided
to implement it.

Write a program that takes a text and a pattern as input, and then applies the KMP algorithm to find
and print all pattern occurrences within the text.

Input format :
The first line of input consists of the text string txt, representing the main string where the pattern
needs to be searched.

The second line of input consists of the pattern string pat, that Raj wants to find within the text as a
string.

Output format :
If the pattern is found, print "Found pattern at index i", where i is the index of the first occurrence of
the pattern in the text.

If the pattern is not found, print "Pattern not found".

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 7/42
Refer to the sample output for the formatting specifications.

Code constraints :
In this scenario, the given test cases will fall under the following constraints:

1 ≤ |txt| ≤ 50

1 ≤ |pat| ≤ 25

The input strings are case-sensitive.

The index starts from 0.

Sample test cases :


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
Input 3 :
ABC
XY
Output 3 :
Pattern not found
Input 4 :
AABAACAADAABAABA
AABA
Output 4 :
Found pattern at index 0
Found pattern at index 9
Found pattern at index 12

Here is the Python implementation of the Knuth-Morris-Pratt (KMP) Algorithm for pattern searching:

python

def compute_lps(pattern):
"""
Computes the Longest Prefix Suffix (LPS) array for the KMP algorithm.
"""
m = len(pattern)
lps = [0] * m

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 8/42
length = 0 # Length of the previous longest prefix suffix
i = 1

while i < m:
if pattern[i] == pattern[length]:
length += 1
lps[i] = length
i += 1
else:
if length != 0:
length = lps[length - 1]
else:
lps[i] = 0
i += 1

return lps

def kmp_search(text, pattern):


"""
KMP algorithm to search for occurrences of the pattern in the text.
"""
n = len(text)
m = len(pattern)
lps = compute_lps(pattern)
i = 0 # Index for text
j = 0 # Index for pattern
found = False

while i < n:
if pattern[j] == text[i]:
i += 1
j += 1

if j == m:
print(f"Found pattern at index {i - j}")
found = True
j = lps[j - 1] # Continue to find other occurrences

elif i < n and pattern[j] != text[i]:


if j != 0:
j = lps[j - 1]
else:
i += 1

if not found:
print("Pattern not found")

# Sample test cases


print("Test Case 1:")
kmp_search("ABABDABACDABABCABAB", "ABABCABAB") # Output: Found pattern at index 10
print("\nTest Case 2:")
kmp_search("ababcababcabcabc", "abc") # Multiple outputs
print("\nTest Case 3:")
kmp_search("ABC", "XY") # Output: Pattern not found
print("\nTest Case 4:")
kmp_search("AABAACAADAABAABA", "AABA") # Multiple outputs

Explanation:

1. Preprocessing the Pattern:


The `compute_lps` function calculates the Longest Prefix Suffix (LPS) array, which helps skip
unnecessary comparisons during pattern matching.
2. Pattern Matching:
Traverse the `text` and compare it with the `pattern` using the `lps` array for efficient
backtracking.
When a mismatch occurs, the `lps` array guides the next position in the pattern to match.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 9/42
3. Output:
For every match, the starting index of the pattern in the text is printed.
If no match is found, it prints `"Pattern not found"`.

Sample Outputs:

Input 1:

plaintext

ABABDABACDABABCABAB
ABABCABAB

Output 1:

plaintext

Found pattern at index 10

Input 2:

plaintext

ababcababcabcabc
abc

Output 2:

plaintext

Found pattern at index 2


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

Input 3:

plaintext

ABC
XY

Output 3:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 10/42
plaintext

Pattern not found

Input 4:

plaintext

AABAACAADAABAABA
AABA

Output 4:

plaintext

Found pattern at index 0


Found pattern at index 9
Found pattern at index 12

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 first 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 fifth 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 specifications.

Sample test cases :


Input 1 :
6
1
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 efficiently find 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):


# 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)

Explanation:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 13/42
1. Three Pointers:
Use three pointers i, j , and k to traverse through arrays arr1, arr2, and arr3, respectively.
2. Finding the Range:
For each combination of elements pointed to by i, j , and k , calculate:
\text{min_val}: The smallest value among the three elements.
\text{max_val}: The largest value among the three elements.
The range is [\text{min_val}, \text{max_val}].
3. Updating the Minimum Range:
If the current range is smaller than the previously found minimum range, update the
minimum range and store \text{min_val} and \text{max_val}.
4. Advancing the Pointer:
Move the pointer of the array with the smallest value since increasing the smallest value has
the potential to reduce the range.
5. Termination:
The loop continues until one of the pointers reaches the end of its array.

Complexity:

Time Complexity: O(N ), where N is the total number of elements in the three arrays (assuming
the arrays are roughly equal in size).
Space Complexity: O(1), as no additional space is used.

Output for Sample Test Cases:

Input 1:

plaintext

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

Output 1:

plaintext

(6, 15)

Input 2:

plaintext

arr1 = [3, 6, 8, 10, 15]


arr2 = [1, 5, 12]
arr3 = [4, 8, 15, 16]

Output 2:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 14/42
plaintext

(3, 5)

Problem Statement

You are given an array of integers. Your task is to find the longest subarray in which the elements
are first sorted in increasing order and then in decreasing order. A subarray is defined as a
contiguous sequence of elements from the original array. Your program should output the length of
this bitonic subarray and the elements it contains.

Input format :
The first line of the input is the size of the array, N.

The second line of the input consists of an array of elements separated by space.

Output format :
The first line displays an integer representing the length of the longest bitonic subarray.

The second line displays the elements of the longest bitonic subarray, separated by a space.

Refer to the sample output for formatting specifications.

Code constraints :
1 ≤ N ≤ 105

Sample test cases :


Input 1 :
7
-4 5 6 8 9 7 -5
Output 1 :
7
-4 5 6 8 9 7 -5
Input 2 :
8
13524632
Output 2 :
5
24632

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 15/42
Here’s the Python implementation to solve the problem of finding the longest bitonic subarray:

python

def find_longest_bitonic_subarray(arr):
n = len(arr)
if n == 0:
return 0, []

# Arrays to store lengths of increasing and decreasing subarrays


inc = [1] * n # Length of increasing subarray ending at index i
dec = [1] * n # Length of decreasing subarray starting at index i

# Compute increasing subarray lengths


for i in range(1, n):
if arr[i] > arr[i - 1]:
inc[i] = inc[i - 1] + 1

# Compute decreasing subarray lengths


for i in range(n - 2, -1, -1):
if arr[i] > arr[i + 1]:
dec[i] = dec[i + 1] + 1

# Find the maximum bitonic subarray length


max_length = 0
start_index = 0
for i in range(n):
bitonic_length = inc[i] + dec[i] - 1
if bitonic_length > max_length:
max_length = bitonic_length
start_index = i

# Extract the elements of the longest bitonic subarray


start = start_index - inc[start_index] + 1
end = start_index + dec[start_index] - 1
bitonic_subarray = arr[start:end + 1]

return max_length, bitonic_subarray

# Sample test cases


print("Test Case 1:")
arr1 = [-4, 5, 6, 8, 9, 7, -5]
length1, subarray1 = find_longest_bitonic_subarray(arr1)
print(length1) # Output: 7
print(*subarray1) # Output: -4 5 6 8 9 7 -5

print("\nTest Case 2:")


arr2 = [1, 3, 5, 2, 4, 6, 3, 2]
length2, subarray2 = find_longest_bitonic_subarray(arr2)
print(length2) # Output: 5
print(*subarray2) # Output: 2 4 6 3 2

Explanation:

1. Increasing Subarray Lengths:


Use the `inc` array to store the length of the longest increasing subarray ending at each
index.
2. Decreasing Subarray Lengths:
Use the `dec` array to store the length of the longest decreasing subarray starting at each
index.
3. Bitonic Length Calculation:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 16/42
At each index i, the bitonic subarray length is given by: \text{bitonic_length} = \text{inc}[i] +
\text{dec}[i] - 1
Subtract 1 because the peak element is counted in both increasing and decreasing subarrays.
4. Finding the Longest Bitonic Subarray:
Iterate through all indices to find the maximum bitonic length and track the start and end
indices of the subarray.
5. Extract the Subarray:
Use the start and end indices to extract the elements of the longest bitonic subarray.

Complexity:

Time Complexity: O(N ), where N is the size of the array.


Computing `inc` and `dec` arrays takes O(N ).
Finding the maximum bitonic length also takes O(N ).
Space Complexity: O(N ), for the `inc` and `dec` arrays.

Sample Outputs:

Input 1:

plaintext

7
-4 5 6 8 9 7 -5

Output 1:

plaintext

7
-4 5 6 8 9 7 -5

Input 2:

plaintext

8
1 3 5 2 4 6 3 2

Output 2:

plaintext

5
2 4 6 3 2

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 17/42
Problem Statement

Assume you are the big boss, and you need to choose the house captain for this week, but in a
mathematical way with some sieving techniques applied.

You have given the contestants a number starting at one and asked them to stand in increasing
order.

THE GAME BEGINS RIGHT NOW!

In the first round, starting from left to right, remove the first number and every alternate number till
the end of the list.

In the second round, repeat the previous step again, but this time, from right to left, remove the
rightmost number and every alternate number from the list.

Keep repeating the steps again, alternating from left to right and from right to left, until only one
number remains.

Given the integer n, which represents the number of housemates, write a code to return the
number of the contestant who lasts in this and is going to be the house captain this week.

Example

Input:

n=9

Output:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 18/42
Explanation:

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]

arr = [2, 4, 6, 8]

arr = [2, 6]

arr = [6]

Input format :
The input consists of an integer representing the number of housemates n.

Output format :
The output prints an integer, representing the number of the contestant who will be the week's
captain.

Refer to the sample output for formatting specifications.

Code constraints :
1 ≤ n ≤ 200

Sample test cases :


Input 1 :
9
Output 1 :
6
Input 2 :
15
Output 2 :
8

Here’s the Python implementation for the described sieving game:

python

def house_captain(n):
arr = list(range(1, n + 1)) # Create a list of contestants from 1 to n
left_to_right = True # Start by removing from left to right

while len(arr) > 1:


if left_to_right:
# Remove alternate numbers starting from the left
arr = arr[1::2]
else:
# Remove alternate numbers starting from the right
arr = arr[:-1][::-1][1::2][::-1]
left_to_right = not left_to_right # Toggle the direction

return arr[0] # The remaining number is the house captain

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 19/42
# Sample test cases
print("Test Case 1:")
n1 = 9
print(house_captain(n1)) # Output: 6

print("\nTest Case 2:")


n2 = 15
print(house_captain(n2)) # Output: 8

Explanation:

1. Initialization:
Start with a list of integers from 1 to n, representing the contestants.
2. Sieving Process:
Alternate between removing every other element from:
Left to right: Start from index 1 and take every second element (arr[1::2]).
Right to left: Reverse the array, remove alternate elements, then reverse it back.
3. Toggle Direction:
Use a boolean variable `left_to_right` to track the direction of removal and toggle it after
each round.
4. Termination:
The process continues until only one element remains in the list.
5. Return Result:
The last remaining element in the list is the house captain.

Complexity:

Time Complexity: O(n log n).


Each sieving step reduces the size of the list approximately by half.
log n rounds are performed, and each round involves operations on a shrinking list.
Space Complexity: O(n), as we maintain the list of contestants.

Sample Outputs:

Input 1:

plaintext

Output 1:

plaintext

Input 2:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 20/42
plaintext

15

Output 2:

plaintext

Problem Statement

A valid number can be split up into these components (in order):

A decimal number or an integer.


(Optional) An 'e' or 'E', is followed by an integer.

A decimal number can be split up into these components (in order):

(Optional) A sign character (either '+' or '-').


One of the following formats:
One or more digits, followed by a dot '.'.
One or more digits, followed by a dot '.', followed by one or more digits.
A dot '.', followed by one or more digits.

An integer can be split up into these components (in order):

(Optional) A sign character (either '+' or '-').


One or more digits.

For example, all the following are valid numbers: ["2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10",
"-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"], while the following are not valid numbers:
["abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"].

Given a string s, return true if s is a valid number.

Company Tags: Facebook

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 21/42
Input format :
The input consists of a string s.

Output format :
The output displays either "true" or "false" depending on whether the input string represents a valid
number or not.

Refer to the sample output for formatting specifications.

Code constraints :
The string s consists of only English letters (both uppercase and lowercase), digits (0-9), plus '+',
minus '-', or dot '.' with at most 20 characters.

Sample test cases :


Input 1 :
0
Output 1 :
true
Input 2 :
e
Output 2 :
false
Input 3 :
.
Output 3 :
false

Here is the Python implementation to determine whether a string s represents a valid number based on
the described rules:

python

import re

def is_valid_number(s):
# Regular expression for a valid number
number_regex = r'^[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$'
# Check if the input matches the regular expression
return bool(re.match(number_regex, s))

# Sample test cases


print("Test Case 1:")
s1 = "0"
print(is_valid_number(s1)) # Output: true

print("\nTest Case 2:")


s2 = "e"
print(is_valid_number(s2)) # Output: false

print("\nTest Case 3:")


s3 = "."

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 22/42
print(is_valid_number(s3)) # Output: false

print("\nTest Case 4:")


s4 = "-123.456e789"
print(is_valid_number(s4)) # Output: true

print("\nTest Case 5:")


s5 = "95a54e53"
print(is_valid_number(s5)) # Output: false

Explanation:

1. Regular Expression:
Optional Sign: `^[+-]?`
The number can optionally start with a `+` or `-`.
Decimal or Integer:
Integer: `\d+`
Decimal: `\d+(\.\d*)?` (e.g., `12.`, `12.34`) or `\.\d+` (e.g., `.34`).
Scientific Notation:
`(e|E)` followed by an optional sign (`[+-]?`) and one or more digits (`\d+`).
Combined Pattern:
`^[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$`
The `^` and `$` ensure that the entire string matches the pattern.
2. Implementation:
Use Python's `re.match` function to check if the input string matches the pattern.
3. Edge Cases:
Valid numbers: `"2"`, `"-90E3"`, `"3e+7"`, `"-.9"`.
Invalid numbers: `"abc"`, `"e"`, `"1e"`, `"."`.

Complexity:

Time Complexity: O(n), where n is the length of the string s, as regular expression matching
traverses the string once.
Space Complexity: O(1), as no additional data structures are used.

Sample Outputs:

Input 1:

plaintext

Output 1:

plaintext

true

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 23/42
Input 2:

plaintext

Output 2:

plaintext

false

Input 3:

plaintext

Output 3:

plaintext

false

Problem Statement

Rajesh has given you a string S of size N(where N is divisible by 4), composed of the letters A, C, T,
and G. It is considered to be steady if each of the four letters occurs exactly n/4 times.

For example, GACT and AAGTGCCT are both steady strings.

You should examine the string S. It is not necessarily steady. Fortunately, You can choose one
(maybe empty) substring and replace it with any string of the same length. Modifying a large
substring should be avoided.

Given a string S, your task is to find the length of the smallest possible substring that can be

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 24/42
replaced to make a steady string.

Input format :
The first line of input consists of an integer, N denoting the size of the string.

The next line of input consists of the string, S.

Output format :
The output prints the length of the minimum length substring that can be replaced to make the
string S stable.

Code constraints :
4 <= N <= 100

Sample test cases :


Input 1 :
8
GAAATAAA
Output 1 :
5
Input 2 :
4
AGAC
Output 2 :
1

Here's the Python solution to find the length of the smallest substring that can be replaced to make the
string steady:

python

from collections import Counter

def min_replacement_length(n, s):


# Calculate the target frequency of each character
target = n // 4
freq = Counter(s) # Frequency count of each character in the string

# If the string is already steady, no replacement is needed


if all(freq[ch] <= target for ch in "ACTG"):
return 0

# Sliding window approach


min_length = n
left = 0

for right in range(n):


# Decrease the frequency of the character at 'right'
freq[s[right]] -= 1

# Check if the remaining string is steady


while all(freq[ch] <= target for ch in "ACTG"):
# Update the minimum length of the substring
min_length = min(min_length, right - left + 1)
# Expand the left boundary of the window
freq[s[left]] += 1

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 25/42
left += 1

return min_length

# Sample test cases


print("Test Case 1:")
n1 = 8
s1 = "GAAATAAA"
print(min_replacement_length(n1, s1)) # Output: 5

print("\nTest Case 2:")


n2 = 4
s2 = "AGAC"
print(min_replacement_length(n2, s2)) # Output: 1

Explanation:

1. Frequency Calculation:
Compute the frequency of each character (`A`, `C`, `T`, `G`) in the string S using Python's
`collections.Counter`.
2. Check for Steady String:
A string is steady if the frequency of each character is less than or equal to N /4. If the initial
string satisfies this condition, no replacement is needed, and we return 0.
3. Sliding Window Approach:
Use a sliding window to find the smallest substring that can be replaced.
As the window grows from the `right` end, decrease the frequency of the character at
`right`.
If the remaining string (excluding the window) is steady, calculate the current window's length
and try shrinking the window from the `left` end.
4. Update Minimum Length:
The minimum length of the substring to be replaced is updated when the window represents
a valid solution.

Complexity:

Time Complexity: O(n), as each character is processed at most twice (once when expanding the
window, and once when shrinking it).
Space Complexity: O(1), since the frequency counter uses constant space for four characters.

Sample Outputs:

Input 1:

plaintext

8
GAAATAAA

Output 1:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 26/42
plaintext

Input 2:

plaintext

4
AGAC

Output 2:

plaintext

Problem Statement

Given an array of distinct elements. The task is to find triplets in the array whose sum is zero.

Example 1

Input:

0 -1 2 -3 1

Output:

-1 0 1

-3 2 1

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 27/42
Explanation:

The triplets with zero-sum are 0 + -1 + 1 = 0 and 2 + -3 + 1 = 0.

Example 2

Input:

12345

Output:

No Triplet Found

In simply way

Here is a Python implementation to find triplets in an array whose sum is zero:

python

def find_triplets(arr):
# Sort the array first
arr.sort()

# List to store the triplets


triplets = []

# Iterate over the array


for i in range(len(arr) - 2):
# Skip duplicate elements for i to avoid duplicate triplets
if i > 0 and arr[i] == arr[i - 1]:
continue

# Two-pointer approach for the remaining elements


left, right = i + 1, len(arr) - 1
while left < right:
current_sum = arr[i] + arr[left] + arr[right]
if current_sum == 0:
triplets.append([arr[i], arr[left], arr[right]])
# Move left and right pointers to avoid duplicates
left += 1
right -= 1
# Skip duplicates on the left and right pointers
while left < right and arr[left] == arr[left - 1]:
left += 1
while left < right and arr[right] == arr[right + 1]:
right -= 1
elif current_sum < 0:
left += 1
else:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 28/42
right -= 1

# If no triplets are found, print the message


if not triplets:
print("No Triplet Found")
else:
for triplet in triplets:
print(*triplet)

# Sample test cases


print("Test Case 1:")
arr1 = [0, -1, 2, -3, 1]
find_triplets(arr1) # Output: -1 0 1 \n -3 2 1

print("\nTest Case 2:")


arr2 = [1, 2, 3, 4, 5]
find_triplets(arr2) # Output: No Triplet Found

Explanation:

1. Sorting:
We first sort the array. Sorting helps us efficiently find triplets using the two-pointer
technique.
2. Two-pointer Technique:
For each element `arr[i]`, we use two pointers: one (`left`) starts just after `i`, and the
other (`right`) starts at the end of the array.
We check the sum of `arr[i] + arr[left] + arr[right]`. If the sum is zero, we found a valid
triplet.
If the sum is less than zero, we move the `left` pointer to the right to increase the sum.
If the sum is greater than zero, we move the `right` pointer to the left to decrease the sum.
3. Skipping Duplicates:
To avoid counting duplicate triplets, we skip duplicate values by checking the previous
element after finding a valid triplet or moving the pointers.
4. Edge Case:
If no triplet is found, we print `"No Triplet Found"`.

Complexity:

Time Complexity: O(n2 ), where n is the number of elements in the array. Sorting the array takes
O(n log n), and the two-pointer traversal takes O(n) for each element.
Space Complexity: O(1) if we don't count the space used by the input array.

Sample Outputs:

Test Case 1:
Input:

plaintext

5
0 -1 2 -3 1

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 29/42
Output:

plaintext

-1 0 1
-3 2 1

Test Case 2:
Input:

plaintext

5
1 2 3 4 5

Output:

plaintext

No Triplet Found

Problem Statement

In a competitive gardening contest, participants are provided with a list of plant heights represented
as positive numbers in a single-line array, each value separated by spaces. The task at hand is to
identify the most significant difference in height between any two plants. The challenge is to select a
pair of plants, denoted as (i, j). The subtracted value of i and j should be the maximum when
compared with different values of i and j in the array, and also the value of j should be greater than
the value of i.

Example

Input:

8 //size of the array

10

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 30/42
2

12

Output:

Explanation:

The difference between the values 0 and 5 is 5. If i = 0 and j = 5, It also satisfies the other condition j
> i.

Input format :
The first line contains a single integer n, which represents the number of integers in the list.

The second line contains n integers in n lines, which represent the list of elements.

Output format :
The output consists of a single integer, which represents the maximum difference between two
integers in the list such that the larger integer appears after the smaller integer.

Sample test cases :


Input 1 :
8
2
4
6
10
12
8
14
20
Output 1 :
7
Input 2 :
8
9
10
2
6
7
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 31/42
12
8
1
Output 2 :
5

To solve this problem, we need to find the maximum difference between two elements in the array such
that the larger element appears after the smaller element. This can be done efficiently by iterating
through the list and keeping track of the minimum value encountered so far. The goal is to maximize the
difference between the current element and the minimum value encountered before it.

Approach:

1. Track the Minimum Value: As we iterate through the list, we will keep track of the minimum value
encountered so far. This ensures that we are always comparing the current element with the
smallest possible element that appears before it.
2. Calculate the Difference: For each element, calculate the difference between the current element
and the minimum value. If this difference is greater than the previously recorded maximum
difference, update the maximum difference.
3. Edge Cases: Ensure that the array has more than one element, as a single element cannot form a
valid pair.

Python Code:

python

def max_difference(n, arr):


# Initialize the minimum value as the first element of the array
min_value = arr[0]
max_diff = float('-inf') # Initialize max_diff to negative infinity

# Traverse the array starting from the second element


for i in range(1, n):
# Calculate the difference between the current element and the min_value so far
max_diff = max(max_diff, arr[i] - min_value)

# Update the min_value to be the smallest encountered so far


min_value = min(min_value, arr[i])

return max_diff

# Sample Test Cases


print("Test Case 1:")
n1 = 8
arr1 = [2, 4, 6, 10, 12, 8, 14, 20]
print(max_difference(n1, arr1)) # Output: 7

print("\nTest Case 2:")


n2 = 8
arr2 = [9, 10, 2, 6, 7, 12, 8, 1]
print(max_difference(n2, arr2)) # Output: 5

Explanation:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 32/42
1. Initialization:
We initialize `min_value` with the first element of the array and set `max_diff` to negative
infinity.
2. Loop Through the Array:
For each element starting from the second element (`i = 1`), calculate the difference
between the current element and the `min_value` so far.
Update `max_diff` with the maximum of its current value and the newly computed difference.
Update `min_value` to the smaller value between the current element and the `min_value`.
3. Return the Result:
The maximum difference is stored in `max_diff`, which is returned at the end.

Complexity:

Time Complexity: O(n), where n is the number of elements in the array. We iterate through the
array only once.
Space Complexity: O(1), since we are using only a few extra variables.

Sample Test Cases:

Test Case 1:
Input:

plaintext

8
2
4
6
10
12
8
14
20

Output:

plaintext

Test Case 2:
Input:

plaintext

8
9
10
2
6
7

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 33/42
12
8
1

Output:

plaintext

Explanation of Outputs:

1. In Test Case 1, the maximum difference occurs between 2 (at index 0) and 9 (at index 7), resulting
in a difference of 7.
2. In Test Case 2, the maximum difference occurs between 2 (at index 2) and 7 (at index 4), resulting
in a difference of 5.

This solution is efficient and handles the problem within the given constraints.

Problem Statement : using normal string

Given two strings, word1, and word2, return the minimum number of operations required to
convert word1 to word2.

You have the following three operations permitted on a word:

Insert a character
Delete a character
Replace a character

Example 1

Input:

horse ros

Output:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 34/42
Explanation:

horse -> rorse (replace 'h' with 'r')

rorse -> rose (remove 'r')

rose -> ros (remove 'e')

Example 2

Input:

intention execution

Output:

Explanation :

intention -> inention (remove 't')

inention -> enention (replace 'i' with 'e')

enention -> exention (replace 'n' with 'x')

exention -> exection (replace 'n' with 'c')

exection -> execution (insert 'u')

This problem is commonly known as the Edit Distance Problem or Levenshtein Distance. The goal is
to determine the minimum number of operations required to convert one string (word1) into another
string (word2). The operations allowed are:

1. Insert a character
2. Delete a character
3. Replace a character

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 35/42
Approach:

We can use dynamic programming to solve this problem efficiently. The idea is to build a 2D table (or
matrix) where each cell represents the minimum number of operations required to convert a substring
of word1 to a substring of word2.
Let's define a 2D array `dp` where:

`dp[i][j]` represents the minimum number of operations required to convert the first `i`
characters of word1 to the first `j` characters of word2.
The final answer will be in `dp[len(word1)][len(word2)]`.

Transition:

To fill the `dp` table:

1. If the characters at `word1[i-1]` and `word2[j-1]` are the same, no operation is needed, and
`dp[i][j] = dp[i-1][j-1]`.
2. If the characters are different, you can:
Insert a character: `dp[i][j-1] + 1`
Delete a character: `dp[i-1][j] + 1`
Replace a character: `dp[i-1][j-1] + 1`

Thus, the recurrence relation is:

dp[i][j] = min(dp[i − 1][j − 1], dp[i − 1][j], dp[i][j − 1]) + 1

Base cases:

`dp[0][j] = j` (It takes `j` insertions to convert an empty string to the first `j` characters of
word2).
`dp[i][0] = i` (It takes `i` deletions to convert the first `i` characters of word1 to an empty
string).

Algorithm:

1. Initialize a 2D array `dp` of size `(len(word1)+1) x (len(word2)+1)`.


2. Use the above recurrence to fill the table.
3. The value at `dp[len(word1)][len(word2)]` gives the minimum number of operations.

Python Code Implementation:

python

def minDistance(word1, word2):


m, n = len(word1), len(word2)

# Initialize the dp table


dp = [[0] * (n + 1) for _ in range(m + 1)]

# Base cases: when one string is empty, all operations are either insertions or deletion
s
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[0][j] = j
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 36/42
# Fill the dp table based on the recurrence
for i in range(1, m + 1):
for j in range(1, n + 1):
if word1[i - 1] == word2[j - 1]:
dp[i][j] = dp[i - 1][j - 1] # No operation needed if characters are the sam
e
else:
dp[i][j] = min(dp[i - 1][j - 1], # Replace
dp[i - 1][j], # Delete
dp[i][j - 1]) + 1 # Insert

# The last cell contains the answer


return dp[m][n]

# Sample Test Cases


print(minDistance("horse", "ros")) # Output: 3
print(minDistance("intention", "execution")) # Output: 5

Explanation of the Code:

1. Initialization:
We first initialize the `dp` table with dimensions `(m+1) x (n+1)` where `m` is the length of
`word1` and `n` is the length of `word2`.
The base cases are filled: `dp[i][0] = i` for all `i` (convert `word1[0..i]` to an empty string),
and `dp[0][j] = j` for all `j` (convert an empty string to `word2[0..j]`).
2. Filling the DP Table:
For each pair of characters `word1[i-1]` and `word2[j-1]`, we check if they are the same. If
they are, no operation is required, so we copy the value from `dp[i-1][j-1]`. If they are
different, we consider the three operations (insert, delete, replace) and take the minimum.
3. Result:
The final result, which is the minimum number of operations, is stored in `dp[m][n]`.

Time and Space Complexity:

Time Complexity: O(m × n), where `m` and `n` are the lengths of the two input strings. This is
because we fill a table of size (m + 1) × (n + 1) and each cell computation takes constant time.

Space Complexity: O(m × n), due to the storage required for the `dp` table.

Sample Test Cases:

1. Test Case 1:
Input:

plaintext

horse
ros

Output:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 37/42
plaintext

2. Test Case 2:
Input:

plaintext

intention
execution

Output:

plaintext

This approach ensures that the problem is solved efficiently even for larger strings, and it handles all
edge cases correctly.

Problem Statement

Given an array of string words and a width maxWidth, format the text such that each line has
exactly maxWidth characters and is fully (left and right) justified.

You should pack your words in a greedy approach; that is, pack as many words as you can in each
line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters.

Extra spaces between words should be distributed as evenly as possible. If the number of spaces on
a line does not divide evenly between words, the empty slots on the left will be assigned more
spaces than the slots on the right.

The last line of text, should be left justified, and no extra space is inserted between words.

Note:

A word is defined as a character sequence consisting of non-space characters only.

Each word's length is guaranteed to be greater than 0 and not exceed maxWidth.

The input array of words contains at least one word.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 38/42
Example

This is an example of text justification

16

Output

[This is an, example of text, justification ]

Explanation

The above output can be interpreted as follows

"This is an",

"example of text",

"justification. "

Input

What must be acknowledgment shall be

16

Output

[What must be, acknowledgment, shall be ]

Explanation

"What must be",

"acknowledgment ",

"shall be "

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 39/42
]

Note that the last line is "shall be " instead of "shall be", because the last line must be left-justified
instead of fully justified.

Note that the second line is also left-justified because it contains only one word.

To solve the problem of text justification, we need to format the words in such a way that they fit into
lines of a specified width (`maxWidth`). Each line must be fully justified, with spaces distributed evenly
between the words.

Steps:

1. Greedy Approach for Word Packing:


We should greedily add words to a line until adding another word would exceed the
`maxWidth`.
2. Space Distribution:
For each line (except the last one), the spaces between words should be distributed as evenly
as possible.
If there are extra spaces (when the spaces cannot be evenly divided between words), the
extra spaces should be placed from the leftmost slot to the right.
3. Last Line:
The last line should be left-justified. This means that there should be only one space
between words, and any remaining space should be added at the end of the line.

Detailed Explanation:

1. Collect words for a line:


For each line, add as many words as possible without exceeding the `maxWidth`.
2. For lines with multiple words:
Calculate the total number of spaces needed.
Distribute these spaces evenly between words.
If there are extra spaces, place them from the leftmost positions.
3. For the last line:
Left justify the words, meaning just place the words with a single space between them, and
then pad the remaining space at the end to meet the `maxWidth`.

Approach:

Step 1: Iterate through the list of words.


Step 2: Try to pack as many words as possible into a line.
Step 3: Calculate the space distribution and justify the line.
Step 4: Handle the last line separately for left justification.

Python Code:

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

def fullJustify(words, maxWidth):


result = []
current_line = []
current_length = 0

for word in words:


# Check if adding this word to the current line exceeds maxWidth
if current_length + len(word) + len(current_line) > maxWidth:
# Distribute spaces and form the current line
spaces_needed = maxWidth - current_length
if len(current_line) == 1:
result.append(current_line[0] + ' ' * spaces_needed)
else:
# Evenly distribute spaces
spaces_per_gap = spaces_needed // (len(current_line) - 1)
extra_spaces = spaces_needed % (len(current_line) - 1)
line = current_line[0]
for i in range(1, len(current_line)):
spaces = ' ' * (spaces_per_gap + (1 if i <= extra_spaces else 0))
line += spaces + current_line[i]
result.append(line)
# Reset for the next line
current_line = []
current_length = 0

# Add the current word to the line


current_line.append(word)
current_length += len(word)

# Handle the last line (left-justified)


last_line = ' '.join(current_line)
result.append(last_line + ' ' * (maxWidth - len(last_line)))

return result

# Sample Test Cases


print(fullJustify(["This", "is", "an", "example", "of", "text", "justification"], 16))
# Output: ["This is an", "example of text", "justification "]

print(fullJustify(["What", "must", "be", "acknowledgment", "shall", "be"], 16))


# Output: ["What must be", "acknowledgment ", "shall be "]

Explanation:

For each word:


If adding the word to the current line exceeds the `maxWidth`, then:
We calculate the total spaces needed.
Distribute spaces evenly between the words.
If there's extra space, add them to the left-most gaps.
After formatting the current line, we reset for the next line.
For the last line:
The last line is left-justified, meaning words are separated by exactly one space, and any
remaining space is added at the end.

Time Complexity:

Time Complexity: O(n), where `n` is the number of words. We iterate through the words once,
and for each line, we distribute spaces, which is done in linear time.
Space Complexity: O(n) for storing the result.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 41/42
Edge Cases:

1. When there's only one word:


It will be left-justified and padded with spaces at the end.
2. When all words can fit in one line:
The entire text will be in a single line with spaces distributed evenly.
3. When `maxWidth` is the size of one word:
Each word will fit exactly into one line without requiring additional spaces.

Sample Test Case Outputs:

Test Case 1:

python

fullJustify(["This", "is", "an", "example", "of", "text", "justification"], 16)

Output:

plaintext

["This is an", "example of text", "justification "]

Test Case 2:

python

fullJustify(["What", "must", "be", "acknowledgment", "shall", "be"], 16)

Output:

plaintext

["What must be", "acknowledgment ", "shall be "]

This solution efficiently formats the text with the desired justification and handles edge cases properly.

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

You might also like