โจทย์เขียนโปรแกรม
โจทย์เขียนโปรแกรม Python เฉลย FizzBuzz Fibonacci Palindrome Sorting Searching Two Sum LeetCode Interview Algorithm OOP
| ระดับ | โจทย์ตัวอย่าง | Concept | LeetCode |
|---|---|---|---|
| Easy | FizzBuzz Two Sum Palindrome | Loop Condition HashMap | #1 #9 #412 |
| Easy | Valid Parentheses Reverse String | Stack String Manipulation | #20 #344 |
| Medium | Longest Substring 3Sum | Sliding Window Two Pointers | #3 #15 |
| Medium | Binary Tree Level Order | BFS Queue Tree | #102 |
| Hard | Merge k Sorted Lists | Heap Divide and Conquer | #23 |
| Hard | Trapping Rain Water | Two Pointers Stack | #42 |
โจทย์พื้นฐาน + เฉลย
# === Basic Programming Problems ===
# 1. FizzBuzz
def fizzbuzz(n):
for i in range(1, n + 1):
if i % 15 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
# 2. Factorial (Recursive)
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
# 3. Fibonacci
def fibonacci(n):
fib = [0, 1]
for i in range(2, n):
fib.append(fib[i-1] + fib[i-2])
return fib[:n]
# 4. Palindrome Check
def is_palindrome(s):
s = s.lower().replace(" ", "")
return s == s[::-1]
# 5. Prime Number Check
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
# 6. Binary Search
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
# 7. GCD (Euclidean Algorithm)
def gcd(a, b):
while b:
a, b = b, a % b
return a
# Test
print("FizzBuzz(15):")
fizzbuzz(15)
print(f"\nFactorial(5) = {factorial(5)}")
print(f"Fibonacci(10) = {fibonacci(10)}")
print(f"Palindrome('racecar') = {is_palindrome('racecar')}")
print(f"Prime(17) = {is_prime(17)}")
print(f"BinarySearch([1,3,5,7,9], 7) = {binary_search([1,3,5,7,9], 7)}")
print(f"GCD(12, 8) = {gcd(12, 8)}")
โจทย์ String + Algorithm
# === String & Algorithm Problems ===
# 1. Two Sum (LeetCode #1)
def two_sum(nums, target):
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return []
# 2. Valid Parentheses (LeetCode #20)
def is_valid_parentheses(s):
stack = []
mapping = {')': '(', ']': '[', '}': '{'}
for char in s:
if char in mapping:
if not stack or stack[-1] != mapping[char]:
return False
stack.pop()
else:
stack.append(char)
return len(stack) == 0
# 3. Anagram Check
def is_anagram(s1, s2):
return sorted(s1.lower()) == sorted(s2.lower())
# 4. Caesar Cipher
def caesar_cipher(text, shift):
result = []
for char in text:
if char.isalpha():
base = ord('A') if char.isupper() else ord('a')
result.append(chr((ord(char) - base + shift) % 26 + base))
else:
result.append(char)
return ''.join(result)
# 5. Maximum Subarray (Kadane's Algorithm)
def max_subarray(nums):
max_sum = current = nums[0]
for num in nums[1:]:
current = max(num, current + num)
max_sum = max(max_sum, current)
return max_sum
# 6. String Compression
def compress_string(s):
if not s:
return s
result = []
count = 1
for i in range(1, len(s)):
if s[i] == s[i-1]:
count += 1
else:
result.append(s[i-1] + str(count))
count = 1
result.append(s[-1] + str(count))
compressed = ''.join(result)
return compressed if len(compressed) < len(s) else s
# Test
print(f"TwoSum([2,7,11,15], 9) = {two_sum([2,7,11,15], 9)}")
print(f"ValidParentheses('()[]{{}}') = {is_valid_parentheses('()[]{}')}")
print(f"Anagram('listen','silent') = {is_anagram('listen','silent')}")
print(f"Caesar('Hello', 3) = {caesar_cipher('Hello', 3)}")
print(f"MaxSubarray([-2,1,-3,4,-1,2,1,-5,4]) = {max_subarray([-2,1,-3,4,-1,2,1,-5,4])}")
print(f"Compress('aabbbcc') = {compress_string('aabbbcc')}")
โจทย์ OOP + Interview
# === OOP & Interview Problems ===
from dataclasses import dataclass
# 1. Stack Implementation
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if self.is_empty():
raise IndexError("Stack is empty")
return self.items.pop()
def peek(self):
if self.is_empty():
raise IndexError("Stack is empty")
return self.items[-1]
def is_empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
# 2. Linked List
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverse_linked_list(head):
prev = None
current = head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
return prev
# 3. Interview Problem Tracker
@dataclass
class Problem:
name: str
difficulty: str
category: str
time_complexity: str
key_concept: str
problems = [
Problem("Two Sum", "Easy", "Array + HashMap",
"O(n)", "HashMap Complement Lookup"),
Problem("Valid Parentheses", "Easy", "Stack",
"O(n)", "Stack LIFO Matching Pairs"),
Problem("Merge Two Sorted Lists", "Easy", "Linked List",
"O(n+m)", "Two Pointer Merge"),
Problem("Maximum Subarray", "Medium", "Dynamic Programming",
"O(n)", "Kadane's Algorithm Local/Global Max"),
Problem("3Sum", "Medium", "Two Pointers",
"O(n²)", "Sort + Two Pointer Skip Duplicates"),
Problem("Longest Substring No Repeat", "Medium", "Sliding Window",
"O(n)", "HashMap + Sliding Window"),
Problem("Merge k Sorted Lists", "Hard", "Heap",
"O(N log k)", "Min Heap Priority Queue"),
]
print("=== Interview Problems ===")
for p in problems:
print(f" [{p.name}] {p.difficulty} | {p.category}")
print(f" Time: {p.time_complexity} | Key: {p.key_concept}")
# Stack Test
s = Stack()
s.push(1); s.push(2); s.push(3)
print(f"\nStack: push 1,2,3 → peek={s.peek()} pop={s.pop()} size={s.size()}")
เคล็ดลับ
- ฝึกทุกวัน: วันละ 1-2 ข้อ LeetCode สม่ำเสมอ
- Pattern: เรียนรู้ Pattern Two Pointers Sliding Window BFS DFS DP
- Brute Force: เริ่มจาก Brute Force ก่อน แล้ว Optimize
- Edge Cases: ทดสอบ Empty Array Single Element Negative
- Explain: พูดอธิบาย Thought Process ขณะ Code
Best Practices สำหรับนักพัฒนา
การเขียนโค้ดที่ดีไม่ใช่แค่ทำให้โปรแกรมทำงานได้ แต่ต้องเขียนให้อ่านง่าย ดูแลรักษาง่าย และ Scale ได้ หลัก SOLID Principles เป็นพื้นฐานสำคัญที่นักพัฒนาทุกู้คืนควรเข้าใจ ได้แก่ Single Responsibility ที่แต่ละ Class ทำหน้าที่เดียว Open-Closed ที่เปิดให้ขยายแต่ปิดการแก้ไข Liskov Substitution ที่ Subclass ต้องใช้แทน Parent ได้ Interface Segregation ที่แยก Interface ให้เล็ก และ Dependency Inversion ที่พึ่งพา Abstraction ไม่ใช่ Implementation
เรื่อง Testing ก็ขาดไม่ได้ ควรเขียน Unit Test ครอบคลุมอย่างน้อย 80% ของ Code Base ใช้ Integration Test ทดสอบการทำงานร่วมกันของ Module ต่างๆ และ E2E Test สำหรับ Critical User Flow เครื่องมือยอดนิยมเช่น Jest, Pytest, JUnit ช่วยให้การเขียน Test เป็นเรื่องง่าย
เรื่อง Version Control ด้วย Git ใช้ Branch Strategy ที่เหมาะกับทีม เช่น Git Flow สำหรับโปรเจคใหญ่ หรือ Trunk-Based Development สำหรับทีมที่ Deploy บ่อย ทำ Code Review ทุก Pull Request และใช้ CI/CD Pipeline ทำ Automated Testing และ Deployment
โจทย์พื้นฐานมีอะไร
FizzBuzz Factorial Fibonacci Palindrome Prime Binary Search GCD Reverse String Sum Digits Temperature Loop Condition Function
โจทย์ String มีอะไร
Anagram Vowels Duplicates Caesar Cipher Longest Prefix Word Count Title Case Valid Parentheses Compress Palindrome Substring
โจทย์ Algorithm มีอะไร
Sorting Bubble Merge Quick Searching Binary Hash Two Sum Kadane Linked List Stack Queue Tree BFS DFS DP Sliding Window Two Pointers
โจทย์สัมภาษณ์งานเป็นอย่างไร
LeetCode Easy 100+ Medium 50+ Blind 75 NeetCode 150 STAR Method Clarification Brute Force Optimize Edge Cases Clean Code ฝึกทุกวัน
สรุป
โจทย์เขียนโปรแกรม Python FizzBuzz Two Sum Palindrome Sorting BFS DFS DP LeetCode Interview OOP Stack Linked List Algorithm
