LeetCode - Blind 75 - Valid Parentheses

The Problem Given a string s containing just the characters '(', ')', '{', '}', '[', and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Every closing bracket has a corresponding open bracket of the same type. Examples Input: s = "()" Output: true Input: s = "()[]{}" Output: true Input: s = "(]" Output: false Input: s = "([])" Output: true Constraints 1 <= s.length <= 10⁴ s consists of parentheses only '()[]{}'. Brute Force Solution func isValid(_ s: String) -> Bool { var s = s while s.contains("()") || s.contains("{}") || s.contains("[]") { s = s.replacingOccurrences(of: "()", with: "") s = s.replacingOccurrences(of: "{}", with: "") s = s.replacingOccurrences(of: "[]", with: "") } return s.isEmpty } Explanation The brute force way to solve this problem is to check if the string contains "()", "{}", "[]" and replace them with an empty string. It’s not a very efficient algorithm and takes O(n²) time because of the while loop and the replacing operation on the entire string. We can optimize it by using a stack data structure. ...

December 5, 2024 · 2 min · Dmytro Chumakov

LeetCode - Blind 75 - Minimum Window Substring

The Problem 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 the empty string "". A substring is a contiguous, non-empty sequence of characters within a string. The test cases will be generated such that the answer is unique. 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. Constraints m == s.length n == t.length 1 <= m, n <= 10⁵ s and t consist of uppercase and lowercase English letters. Follow-up: Could you find an algorithm that runs in O(m + n) time? ...

December 3, 2024 · 4 min · Dmytro Chumakov

LeetCode - Blind 75 - Longest Repeating Character Replacement

The problem You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times. Return the length of the longest substring containing the same letter you can get after performing the above operations. Examples Input: s = "ABAB", k = 2 Output: 4 Explanation: Replace the two 'A's with two 'B's or vice versa. Input: s = "AABABBA", k = 1 Output: 4 Explanation: Replace the one 'A' in the middle with 'B' and form "AABBBBA". The substring "BBBB" has the longest repeating letters, which is 4. There may exist other ways to achieve this answer too. Constraints 1 <= s.length <= 105 s consists of only uppercase English letters. 0 <= k <= s.length Brute force solution func characterReplacement(_ s: String, _ k: Int) -> Int { let n = s.count let s = Array(s) var res = 0 for i in 0 ..< n { var count: [Character: Int] = [:] var maxF = 0 for j in i ..< n { count[s[j], default: 0] += 1 maxF = max(maxF, count[s[j]]!) let windowSize = (j - i + 1) let numOfCharsToReplace = (windowSize - maxF) let canReplace = (numOfCharsToReplace <= k) if canReplace { res = max(res, windowSize) } } } return res } Explanation First things first, we need to figure out which character we are going to replace. We can do this by using a dictionary. This way, we can calculate the most frequent character in the substring. After that, we will be able to calculate the number of characters to replace and check if we can replace the character. This algorithm is not very fast and takes O(n^2) time. We can improve it further and optimize it to achieve O(n) time complexity. ...

November 29, 2024 · 3 min · Dmytro Chumakov

LeetCode - Blind 75 - Longest Substring Without Repeating Characters

The Problem Given a string s, find the length of the longest substring without repeating characters. A substring is a contiguous non-empty sequence of characters within a string. Examples Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Input: s = "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Input: s = "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Notice that the answer must be a substring. "pwke" is a subsequence and not a substring. Constraints 0 <= s.length <= 5 * 10⁴ s consists of English letters, digits, symbols, and spaces. Brute Force Solution func lengthOfLongestSubstring(_ s: String) -> Int { let n = s.count var res = 0 for i in 0 ..< n { var chars: [Character] = [] for j in i ..< n { if chars.contains(s[j]) { break } chars.append(s[j]) } res = max(res, chars.count) } return res } Explanation Let’s start by visualizing the problem: ...

November 26, 2024 · 2 min · Dmytro Chumakov

LeetCode - Blind 75 - Best Time to Buy and Sell Stock

The problem You are given an array prices where prices[i] is the price of a given stock on the i-th day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. Examples Input: prices = [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. Input: prices = [7,6,4,3,1] Output: 0 Explanation: In this case, no transactions are done and the max profit = 0. Constraints 1 <= prices.length <= 10⁵ 0 <= prices[i] <= 10⁴ Brute force solution func maxProfit(_ prices: [Int]) -> Int { let n = prices.count var res = 0 for i in 0 ..< n { for j in i + 1 ..< n { let profit = prices[j] - prices[i] if profit > 0 { res = max(res, profit) } } } return res } Explanation We can start with a brute force solution and find a way to a more optimal solution as we go. By visualizing the problem using input from example 1 [7,1,5,3,6,4]: ...

November 22, 2024 · 2 min · Dmytro Chumakov