Skip to content

Commit 9a230f7

Browse files
authored
Add files via upload
1 parent 9265c95 commit 9a230f7

7 files changed

+363
-0
lines changed

Two_Pointers/3sum.py

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
def find_sum_of_three(nums, target):
2+
# Sort the array in ascending order
3+
nums.sort()
4+
5+
# for loop will cycle through each index of nums for i
6+
for i in range(0, len(nums)-2):
7+
# Pointers start positions must be defined inside for loop, so the reset at each loop
8+
pointer_1 = i + 1
9+
pointer_2 = len(nums) - 1
10+
# Ensure that each combo of values is tried without overlap of pointers
11+
while pointer_1 < pointer_2:
12+
# Calculate sum
13+
sum = nums[i] + nums[pointer_1] + nums[pointer_2]
14+
# If a match is found, return True
15+
if sum == target:
16+
return True
17+
# If we're less than target, increase pointer_1 value
18+
elif sum < target:
19+
pointer_1 += 1
20+
# If we're greater than target, decrease pointer_2 value
21+
elif sum > target:
22+
pointer_2 -= 1
23+
# Iterate through i
24+
i += 1
25+
# If no match found, return False
26+
return False
27+
28+
29+
30+
# Driver code
31+
def main():
32+
nums_lists = [[3, 7, 1, 2, 8, 4, 5],
33+
[-1, 2, 1, -4, 5, -3],
34+
[2, 3, 4, 1, 7, 9],
35+
[1, -1, 0],
36+
[2, 4, 2, 7, 6, 3, 1]]
37+
38+
targets = [10, 7, 20, -1, 8]
39+
40+
for i in range(len(nums_lists)):
41+
print(i + 1, ".\tInput array: ", nums_lists[i], sep="")
42+
if find_sum_of_three(nums_lists[i], targets[i]):
43+
print("\tSum for", targets[i], "exists")
44+
else:
45+
print("\tSum for", targets[i], "does not exist")
46+
print("-"*100)
47+
48+
if __name__ == '__main__':
49+
main()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
# Template for linked list node class
2+
class LinkedListNode:
3+
def __init__(self, data, next=None):
4+
self.data = data
5+
self.next = next
6+
7+
# Template for the linked list
8+
class LinkedList:
9+
def __init__(self):
10+
self.head = None
11+
12+
# Method to insert a node at the head of the linked list
13+
def insert_node_at_head(self, node):
14+
if self.head:
15+
node.next = self.head
16+
self.head = node
17+
18+
# Method to create a linked list from a list of values
19+
def create_linked_list(self, values):
20+
for value in reversed(values):
21+
self.insert_node_at_head(LinkedListNode(value))
22+
23+
24+
25+
26+
27+
def remove_nth_last_node(head, n):
28+
right = head
29+
left = head
30+
31+
# Move the right pointer forward n steps
32+
for i in range(n):
33+
right = right.next
34+
35+
# If right is None after moving n steps, we need to remove the head (i.e. n exceeds length of linked list)
36+
if right is None:
37+
return head.next # Removing the head
38+
39+
# Move both pointers forward until right reaches the end
40+
while right.next is not None:
41+
right = right.next
42+
left = left.next
43+
44+
# Remove the Nth node from the end
45+
left.next = left.next.next
46+
47+
return head
48+
49+
50+
51+
52+
53+
# Function to print the linked list
54+
def print_list_with_forward_arrow(head):
55+
current = head
56+
while current:
57+
print(current.data, end=" -> " if current.next else "")
58+
current = current.next
59+
print()
60+
61+
# Driver code
62+
def main():
63+
lists = [
64+
[23, 89, 10, 5, 67, 39, 70, 28],
65+
[34, 53, 6, 95, 38, 28, 17, 63, 16, 76],
66+
[288, 224, 275, 390, 4, 383, 330, 60, 193],
67+
[1, 2, 3, 4, 5, 6, 7, 8, 9],
68+
[69, 8, 49, 106, 116, 112, 104, 129, 39, 14, 27, 12]
69+
]
70+
n = [4, 1, 6, 9, 11]
71+
72+
for i in range(len(n)):
73+
input_linked_list = LinkedList()
74+
input_linked_list.create_linked_list(lists[i])
75+
print(i + 1, ". Linked List:\t", end='')
76+
print_list_with_forward_arrow(input_linked_list.head)
77+
print("n = ", n[i])
78+
result = remove_nth_last_node(input_linked_list.head, n[i])
79+
print("Updated Linked List:\t", end='')
80+
print_list_with_forward_arrow(result)
81+
print("-" * 100)
82+
83+
if __name__ == '__main__':
84+
main()

Two_Pointers/reverse_words_string.py

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
def reverse_words(sentence):
2+
# Remove any leading or trailing spaces from the sentence
3+
sentence = sentence.strip()
4+
5+
# Split the string into words
6+
words = sentence.split()
7+
8+
# Reverse order of words using two pointers
9+
start = 0
10+
end = len(words) - 1
11+
12+
while start < end:
13+
words[start], words[end] = words[end], words[start]
14+
start += 1
15+
end -= 1
16+
17+
# Join words back into sentence
18+
return ' '.join(words)
19+
20+
21+
22+
23+
# Driver code
24+
def main():
25+
string_to_reverse = ["Hello World",
26+
"a string with multiple spaces",
27+
"Case Sensitive Test Case 1234",
28+
"a 1 b 2 c 3 d 4 e 5",
29+
" trailing spaces",
30+
"case test interesting an is this"]
31+
32+
for i in range(len(string_to_reverse)):
33+
print(i + 1, ".\tOriginal string: '" + "".join(string_to_reverse[i]), "'", sep='')
34+
result = reverse_words(string_to_reverse[i])
35+
36+
print("\tReversed string: '" + "".join(result), "'", sep='')
37+
print("-" * 100)
38+
39+
40+
if __name__ == '__main__':
41+
main()

Two_Pointers/sort_colors.py

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
def sort_colors(colors):
2+
3+
# Initialize starting indices of pointers
4+
start = 0
5+
current = 0
6+
end = len(colors) - 1
7+
8+
# End loop when current index becomes greater than end index
9+
while current <= end:
10+
# Swap start and current values
11+
if colors[current] == 0:
12+
colors[start], colors[current] = colors[current], colors[start]
13+
start += 1
14+
current += 1
15+
# No swap of values, continue to next iteration in the loop
16+
elif colors[current] == 1:
17+
current += 1
18+
# Swap end and current values
19+
else:
20+
colors[end], colors[current] = colors[current], colors[end]
21+
end -= 1
22+
23+
return colors
24+
25+
26+
27+
28+
# Driver code
29+
def main():
30+
inputs = [[0, 1, 0], [1, 1, 0, 2], [2, 1, 1, 0, 0], [2, 2, 2, 0, 1, 0], [2, 1, 1, 0, 1, 0, 2]]
31+
32+
# Iterate over the inputs and print the sorted array for each
33+
for i in range(len(inputs)):
34+
colors=inputs[i]
35+
print(i + 1, ".\tcolors:", colors)
36+
sort_colors(colors)
37+
print("\n\tThe sorted array is:", colors)
38+
print("-" * 100)
39+
40+
if __name__ == "__main__":
41+
main()

Two_Pointers/valid_palindrome.py

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
def is_palindrome(s):
2+
# Initialize pointer 1 at the start of the string and pointer 2 at end of the string
3+
pointer_1 = 0
4+
pointer_2 = len(s) - 1
5+
6+
# Continue to loop until the pointers meet at the midpoint
7+
while pointer_1 <= pointer_2:
8+
# If there's a match, move pointers inward
9+
if s[pointer_1] == s[pointer_2]:
10+
pointer_1 += 1
11+
pointer_2 -= 1
12+
else:
13+
# If there's no match
14+
return False
15+
# If we make it to the midpoint and all match return True
16+
return True
17+
18+
19+
# Driver code
20+
def main():
21+
test_cases = ["RACECAR", "ABBA", "TART"]
22+
i = 1
23+
for s in test_cases:
24+
print("Test Case #", i)
25+
print(is_palindrome(s))
26+
print("-" * 100, end="\n\n")
27+
i = i + 1
28+
29+
if __name__ == '__main__':
30+
main()

Two_Pointers/valid_palindrome_II.py

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
def is_palindrome(string):
2+
3+
# Initialize one pointer at the start and one at the end
4+
start = 0
5+
end = len(string) - 1
6+
7+
while start < end:
8+
if string[start] == string[end]:
9+
start += 1
10+
end -= 1
11+
else:
12+
# If there's a mismatch, check two cases:
13+
# 1. Skip the start character
14+
# 2. Skip the end character
15+
skip_start = check_palindrome(string, start + 1, end)
16+
skip_end = check_palindrome(string, start, end - 1)
17+
return skip_start or skip_end
18+
19+
return True
20+
21+
def check_palindrome(string, left, right):
22+
while left < right:
23+
if string[left] != string[right]:
24+
return False
25+
left += 1
26+
right -= 1
27+
return True
28+
29+
30+
31+
# Driver code
32+
def main():
33+
test_cases = [
34+
"madame",
35+
"dead",
36+
"abca",
37+
"tebbem",
38+
"eeccccbebaeeabebccceea"
39+
]
40+
41+
i = 1
42+
for s in test_cases:
43+
print("Test Case #", i)
44+
print(f"Input: '{s}'")
45+
result = is_palindrome(s)
46+
print("Is valid palindrome after at most one removal?:", result)
47+
print("-" * 100, end="\n\n")
48+
i += 1
49+
50+
if __name__ == '__main__':
51+
main()
+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
def valid_word_abbreviation(word, abbr):
2+
3+
# Initialize pointer start locations
4+
word_pointer = 0
5+
abbr_pointer = 0
6+
7+
# Continue loop until end of abbr in reached
8+
while abbr_pointer < len(abbr):
9+
10+
# Check if alphabetical character
11+
if abbr[abbr_pointer].isalpha():
12+
13+
# Verify that alphabetical characters match between word and abbr
14+
if word_pointer < len(word) and word[word_pointer] == abbr[abbr_pointer]:
15+
word_pointer += 1
16+
17+
else:
18+
return False
19+
20+
abbr_pointer += 1
21+
22+
# Check if numerical character
23+
elif abbr[abbr_pointer].isdigit():
24+
25+
# Check for leading zero
26+
if abbr[abbr_pointer] == '0':
27+
return False
28+
29+
# Capture entire numerical value
30+
start = abbr_pointer
31+
32+
while abbr_pointer < len(abbr) and abbr[abbr_pointer].isdigit():
33+
abbr_pointer += 1
34+
35+
# Convert numerical substring to an integer
36+
num = int(abbr[start:abbr_pointer])
37+
word_pointer += num
38+
39+
# Check that we didn't exceed length of word
40+
if word_pointer > len(word):
41+
return False
42+
43+
# If neither alphabetical or numerical scenario is satisfied
44+
else:
45+
return False
46+
47+
# Check that we reached the end of the word
48+
if word_pointer != len(word):
49+
return False
50+
51+
return True
52+
53+
54+
55+
56+
def main():
57+
words = ["a", "a", "abcdefghijklmnopqrst", "abcdefghijklmnopqrst", "word", "internationalization", "localization"]
58+
abbreviations = ["a", "b", "a18t", "a19t", "w0rd", "i18n", "l12n"]
59+
60+
for i in range(len(words)):
61+
print(i + 1, ".\t word: '", words[i], "'", sep="")
62+
print("\t abbr: ", abbreviations[i], "'", sep="")
63+
print(f"\n\t Is '{abbreviations[i]}' a valid abbreviation for the word '{words[i]}'? ", valid_word_abbreviation(words[i], abbreviations[i]), sep="")
64+
print("-" * 100)
65+
66+
if __name__ == '__main__':
67+
main()

0 commit comments

Comments
 (0)