premaram/Programming_Challenges_Hub
1
1import streamlit as st2import io3import contextlib4 5def Q1():6 7 st.title("2243. Calculate Digit Sum of a String")8 9 st.markdown("[Visit Leetcode](https://leetcode.com/problems/calculate-digit-sum-of-a-string/description/) for a better experience.")10 11 # Create two columns: left for question, right for code input12 col1, col2 = st.columns(2)13 14 # Left column: Display the problem description15 with col1:16 st.write("""17 **Problem**: You are given a string `s` consisting of digits and an integer `k`.18 19 A round can be completed if the length of `s` is greater than `k`. In one round, do the following:20 21 1. Divide `s` into consecutive groups of size `k` such that the first `k` characters are in the first group, 22 the next `k` characters are in the second group, and so on. Note that the size of the last group can 23 be smaller than `k`.24 2. Replace each group of `s` with a string representing the sum of all its digits. 25 For example, `"346"` is replaced with `"13"` because `3 + 4 + 6 = 13`.26 3. Merge consecutive groups together to form a new string. If the length of the string is greater than `k`, 27 repeat from step 1.28 29 Return `s` after all rounds have been completed.30 31 **Example 1**:32 - Input: `s = "11111222223", k = 3`33 - Output: `"135"`34 - Explanation: 35 - For the first round, we divide `s` into groups of size 3: `"111"`, `"112"`, `"222"`, and `"23"`.36 - Then we calculate the digit sum of each group: 37 - `1 + 1 + 1 = 3`, 38 - `1 + 1 + 2 = 4`, 39 - `2 + 2 + 2 = 6`, 40 - `2 + 3 = 5`. 41 - So, `s` becomes `"3" + "4" + "6" + "5" = "3465"` after the first round.42 - For the second round, we divide `s` into `"346"` and `"5"`.43 - Then we calculate the digit sum of each group: 44 - `3 + 4 + 6 = 13`, 45 - `5 = 5`. 46 - So, `s` becomes `"13" + "5" = "135"` after the second round. 47 - Now, `s.length <= k`, so we return `"135"` as the answer.48 49 **Example 2**:50 - Input: `s = "00000000", k = 3`51 - Output: `"000"`52 - Explanation: 53 - We divide `s` into `"000"`, `"000"`, and `"00"`.54 - Then we calculate the digit sum of each group: 55 - `0 + 0 + 0 = 0`, 56 - `0 + 0 + 0 = 0`, 57 - `0 + 0 = 0`. 58 - `s` becomes `"0" + "0" + "0" = "000"`, whose length is equal to `k`, so we return `"000"`.59 60 **Constraints**:61 - `1 <= s.length <= 100`62 - `2 <= k <= 100`63 - `s` consists of digits only.64 """)65 66 # Create an expander for the topics67 with st.expander("Topics", expanded=False):68 st.write(""" 69 - **String**70 - **Simulation**71 """)72 73 with st.expander("Hint",expanded=False):74 st.write("Try simulating the entire process to find the final answer.")75 76 77 with st.expander("Sample Answer (NOTE: every question has different solutions)", expanded=False):78 st.code("""79 80def digitSum(s, k):81 def divideString(s, k):82 l, n = [], len(s)83 for i in range(0, n, k):84 l.append(s[i:min(i + k, n)])85 return l86 while len(s)>k:87 arr, temp = divideString(s, k), [] 88 for group in arr: 89 group_sum = 090 for digit in group:91 group_sum += int(digit)92 temp.append(str(group_sum)) 93 s = ''.join(temp) 94 return s95 """)96 97 with st.expander("Flowchart of Sample Answer", expanded=False):98 st.image("images/intermediate/1.png")99 100 # Right column: Provide code editor for users to solve the problem101 with col2:102 st.header("Solve the Problem")103 104 # Display a code editor for the user to write their solution105 code_input = st.text_area(106 "Write your Python function here:",107 height=300,108 value="""109def digitSum(s, k):110 # Your code goes here111 pass112""")113 114 # Predefined test cases to evaluate the user's function115 test_cases = [116 {"input": ("11111222223", 3), "expected": "135"},117 {"input": ("00000000", 3), "expected": "000"},118 ]119 120 # Display the test cases in an expander121 for i, case in enumerate(test_cases):122 with st.expander(f"View Test Case {i + 1}", expanded=False):123 st.write(f"**Test Case {i + 1}:**")124 st.write(f"- Input: `{case['input']}`")125 st.write(f"- Expected Output: `{case['expected']}`")126 127 # Button to execute the code128 if st.button("Run Code"):129 buffer = io.StringIO()130 131 # Try to safely execute the user code132 try:133 # Redirect stdout to buffer and run the code134 with contextlib.redirect_stdout(buffer):135 exec_globals = {}136 exec(code_input, exec_globals) # Execute the user code137 138 # Check if the function `digitSum` is defined139 if "digitSum" in exec_globals:140 digitSum = exec_globals['digitSum'] # Get the function141 142 # Run the function on all test cases143 all_passed = True144 for i, case in enumerate(test_cases):145 input_val = case["input"]146 expected_val = case["expected"]147 148 try:149 result = digitSum(*input_val)150 if result == expected_val:151 st.write(f"Test case {i + 1} passed!")152 else:153 all_passed = False154 st.write(f"Test case {i + 1} failed: Expected {expected_val}, but got {result}")155 except Exception as e:156 all_passed = False157 st.write(f"Test case {i + 1} raised an error: {e}")158 159 if all_passed:160 st.success("All test cases passed!")161 else:162 st.error("Some test cases failed. Please review your code.")163 else:164 st.error("Function `digitSum` not defined. Please define the function to proceed.")165 except Exception as e:166 st.error(f"Error executing code: {e}")167 168 # Display any print outputs or errors captured169 output = buffer.getvalue()170 if output:171 st.subheader("Execution Output:")172 st.text(output)173 174 175 176 177def Q2():178 st.title("1470. Shuffle the Array")179 180 st.markdown("[Visit Leetcode](https://leetcode.com/problems/shuffle-the-array/) for a better experience.")181 182 # Create two columns: left for question, right for code input183 col1, col2 = st.columns(2)184 185 # Left column: Display the problem description186 with col1:187 st.write("""188 **Problem**: Given the array `nums` consisting of `2n` elements in the form 189 `[x1,x2,...,xn,y1,y2,...,yn]`, return the array in the form `[x1,y1,x2,y2,...,xn,yn]`.190 191 **Example 1**:192 - Input: `nums = [2,5,1,3,4,7], n = 3`193 - Output: `[2,3,5,4,1,7]` 194 - Explanation: Since `x1=2`, `x2=5`, `x3=1`, `y1=3`, `y2=4`, `y3=7`, then the answer is `[2,3,5,4,1,7]`.195 196 **Example 2**:197 - Input: `nums = [1,2,3,4,4,3,2,1], n = 4`198 - Output: `[1,4,2,3,3,2,4,1]`199 200 **Example 3**:201 - Input: `nums = [1,1,2,2], n = 2`202 - Output: `[1,2,1,2]`203 204 **Constraints**:205 - `1 <= n <= 500`206 - `nums.length == 2n`207 - `1 <= nums[i] <= 10^3208 """)209 210 # Create an expander for the topics211 with st.expander("Topics", expanded=False):212 st.write(""" 213 - **Array**214 """)215 216 with st.expander("Hint",expanded=False):217 st.write("Use two pointers to create the new array of 2n elements. The first starting at the beginning and the other starting at (n+1)th position. Alternate between them and create the new array.")218 219 with st.expander("Sample Answer (NOTE: every question has different solutions)", expanded=False):220 st.code("""221 def shuffle(nums, n):222 left = 0223 right = n 224 ans = []225 226 while right < len(nums):227 ans.append(nums[left])228 ans.append(nums[right])229 left+=1230 right+=1231 return ans232 """)233 234 with st.expander("Flowchart of Sample Answer", expanded=False):235 st.image("images/intermediate/2.png")236 237 # Right column: Provide code editor for users to solve the problem238 with col2:239 st.header("Solve the Problem")240 241 # Display a code editor for the user to write their solution242 code_input = st.text_area(243 "Write your Python function here:",244 height=300,245 value="""246def shuffle(nums, n) :247 # Your code goes here248 pass249""")250 251 # Predefined test cases to evaluate the user's function252 test_cases = [253 {"input": ([2,5,1,3,4,7], 3), "expected": [2,3,5,4,1,7]},254 {"input": ([1,2,3,4,4,3,2,1], 4), "expected": [1,4,2,3,3,2,4,1]},255 {"input": ([1,1,2,2], 2), "expected": [1,2,1,2]},256 {"input": ([10,20,30,40,50,60], 3), "expected": [10,40,20,50,30,60]},257 ]258 259 # Display the test cases in an expander260 for i, case in enumerate(test_cases):261 with st.expander(f"View Test Case {i + 1}", expanded=False):262 st.write(f"**Test Case {i + 1}:**")263 st.write(f"- Input: `{case['input']}`")264 st.write(f"- Expected Output: `{case['expected']}`")265 266 # Button to execute the code267 if st.button("Run Code"):268 buffer = io.StringIO()269 270 # Try to safely execute the user code271 try:272 # Redirect stdout to buffer and run the code273 with contextlib.redirect_stdout(buffer):274 exec_globals = {}275 exec(code_input, exec_globals) # Execute the user code276 277 # Check if the function `shuffle` is defined278 if "shuffle" in exec_globals:279 shuffle = exec_globals['shuffle'] # Get the function280 281 # Run the function on all test cases282 all_passed = True283 for i, case in enumerate(test_cases):284 input_val = case["input"]285 expected_val = case["expected"]286 287 try:288 result = shuffle(*input_val)289 if result == expected_val:290 st.write(f"Test case {i + 1} passed!")291 else:292 all_passed = False293 st.write(f"Test case {i + 1} failed: Expected {expected_val}, but got {result}")294 except Exception as e:295 all_passed = False296 st.write(f"Test case {i + 1} raised an error: {e}")297 298 if all_passed:299 st.success("All test cases passed!")300 else:301 st.error("Some test cases failed. Please review your code.")302 else:303 st.error("Function `shuffle` not defined. Please define the function to proceed.")304 except Exception as e:305 st.error(f"Error executing code: {e}")306 307 # Display any print outputs or errors captured308 output = buffer.getvalue()309 if output:310 st.subheader("Execution Output:")311 st.text(output)312 313def Q3():314 st.title("1431. Kids With the Greatest Number of Candies")315 316 st.markdown("[Visit Leetcode](https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/description/) for a better experience.")317 318 # Create two columns: left for question, right for code input319 col1, col2 = st.columns(2)320 321 # Left column: Display the problem description322 with col1:323 st.write("""324 **Problem**: There are n kids with candies. You are given an integer array `candies`, 325 where `candies[i]` represents the number of candies the ith kid has, and an integer `extraCandies`, 326 denoting the number of extra candies that you have.327 328 Return a boolean array `result` of length n, where `result[i]` is true if, after giving the ith kid all 329 the `extraCandies`, they will have the greatest number of candies among all the kids, or false otherwise.330 331 **Example 1**:332 - Input: `candies = [2,3,5,1,3], extraCandies = 3`333 - Output: `[true,true,true,false,true]` 334 335 **Example 2**:336 - Input: `candies = [4,2,1,1,2], extraCandies = 1`337 - Output: `[true,false,false,false,false]` 338 339 **Example 3**:340 - Input: `candies = [12,1,12], extraCandies = 10`341 - Output: `[true,false,true]`342 343 **Constraints**:344 - `n == candies.length`345 - `2 <= n <= 100`346 - `1 <= candies[i] <= 100`347 - `1 <= extraCandies <= 50348 """)349 350 # Create an expander for the topics351 with st.expander("Topics", expanded=False):352 st.write(""" 353 - **Array**354 355 """)356 357 with st.expander("Hint", expanded=False):358 st.write("For each kid check if candies[i] + extraCandies ≥ maximum in Candies[i].")359 360 with st.expander("Sample Answer (NOTE: every question has different solutions)", expanded=False):361 st.code("""362 def kidsWithCandies(candies, extraCandies):363 max_val = max(candies) 364 result = [] 365 366 for i in range(len(candies)):367 result.append(candies[i] + extraCandies >= max_val)368 369 return result370 """)371 with st.expander("Flowchart of Sample Answer", expanded=False):372 st.image("images/intermediate/3.png")373 374 # Right column: Provide code editor for users to solve the problem375 with col2:376 st.header("Solve the Problem")377 378 # Display a code editor for the user to write their solution379 code_input = st.text_area(380 "Write your Python function here:",381 height=300,382 value="""383def kidsWithCandies(candies, extraCandies):384 # Your code goes here385 pass386""")387 388 # Predefined test cases to evaluate the user's function389 test_cases = [390 {"input": ([2,3,5,1,3], 3), "expected": [True, True, True, False, True]},391 {"input": ([4,2,1,1,2], 1), "expected": [True, False, False, False, False]},392 {"input": ([12,1,12], 10), "expected": [True, False, True]},393 ]394 395 # Display the test cases in an expander396 for i, case in enumerate(test_cases):397 with st.expander(f"View Test Case {i + 1}", expanded=False):398 st.write(f"**Test Case {i + 1}:**")399 st.write(f"- Input: `{case['input']}`")400 st.write(f"- Expected Output: `{case['expected']}`")401 402 # Button to execute the code403 if st.button("Run Code"):404 buffer = io.StringIO()405 406 # Try to safely execute the user code407 try:408 # Redirect stdout to buffer and run the code409 with contextlib.redirect_stdout(buffer):410 exec_globals = {}411 exec(code_input, exec_globals) # Execute the user code412 413 # Check if the function `kidsWithCandies` is defined414 if "kidsWithCandies" in exec_globals:415 kidsWithCandies = exec_globals['kidsWithCandies'] # Get the function416 417 # Run the function on all test cases418 all_passed = True419 for i, case in enumerate(test_cases):420 input_val = case["input"]421 expected_val = case["expected"]422 423 try:424 result = kidsWithCandies(*input_val)425 if result == expected_val:426 st.write(f"Test case {i + 1} passed!")427 else:428 all_passed = False429 st.write(f"Test case {i + 1} failed: Expected {expected_val}, but got {result}")430 except Exception as e:431 all_passed = False432 st.write(f"Test case {i + 1} raised an error: {e}")433 434 if all_passed:435 st.success("All test cases passed!")436 else:437 st.error("Some test cases failed. Please review your code.")438 else:439 st.error("Function `kidsWithCandies` not defined. Please define the function to proceed.")440 except Exception as e:441 st.error(f"Error executing code: {e}")442 443 # Display any print outputs or errors captured444 output = buffer.getvalue()445 if output:446 st.subheader("Execution Output:")447 st.text(output)448 449def Q4():450 st.title("1512. Number of Good Pairs")451 452 st.markdown("[Visit Leetcode](https://leetcode.com/problems/number-of-good-pairs/description/) for a better experience.")453 454 # Create two columns: left for question, right for code input455 col1, col2 = st.columns(2)456 457 # Left column: Display the problem description458 with col1:459 st.write("""460 **Problem**: Given an array of integers `nums`, return the number of good pairs.461 462 A pair (i, j) is called good if `nums[i] == nums[j]` and `i < j`.463 464 **Example 1**:465 - Input: `nums = [1,2,3,1,1,3]`466 - Output: `4` 467 - Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.468 469 **Example 2**:470 - Input: `nums = [1,1,1,1]`471 - Output: `6` 472 - Explanation: Each pair in the array are good.473 474 **Example 3**:475 - Input: `nums = [1,2,3]`476 - Output: `0` 477 478 **Constraints**:479 - `1 <= nums.length <= 100`480 - `1 <= nums[i] <= 100481 """)482 483 # Create an expander for the topics484 with st.expander("Topics", expanded=False):485 st.write(""" 486 - **Array**487 - **Hash Table**488 - **Math**489 - **counting**490 """)491 492 with st.expander("Hint", expanded=False):493 st.write("Count how many times each number appears. If a number appears n times, then n * (n – 1) // 2 good pairs can be made with this number.")494 495 with st.expander("Sample Answer (NOTE: every question has different solutions)", expanded=False):496 st.code("""497from collections import Counter 498 499def numIdenticalPairs(nums):500 frequency = Counter(nums) 501 counter = 0 502 for count in frequency.values():503 if count > 1:504 counter += (count * (count - 1)) // 2 505 return counter506 507 """)508 509 with st.expander("Flowchart of Sample Answer", expanded=False):510 st.image("images/intermediate/4.png")511 512 # Right column: Provide code editor for users to solve the problem513 with col2:514 st.header("Solve the Problem")515 516 # Display a code editor for the user to write their solution517 code_input = st.text_area(518 "Write your Python function here:",519 height=300,520 value="""521def numIdenticalPairs(nums):522 # Your code goes here523 pass524""")525 526 # Predefined test cases to evaluate the user's function527 test_cases = [528 {"input": [1, 2, 3, 1, 1, 3], "expected": 4},529 {"input": [1, 1, 1, 1], "expected": 6},530 {"input": [1, 2, 3], "expected": 0},531 ]532 533 # Display the test cases in an expander534 for i, case in enumerate(test_cases):535 with st.expander(f"View Test Case {i + 1}", expanded=False):536 st.write(f"**Test Case {i + 1}:**")537 st.write(f"- Input: `{case['input']}`")538 st.write(f"- Expected Output: `{case['expected']}`")539 540 # Button to execute the code541 if st.button("Run Code"):542 buffer = io.StringIO()543 544 # Try to safely execute the user code545 try:546 # Redirect stdout to buffer and run the code547 with contextlib.redirect_stdout(buffer):548 exec_globals = {}549 exec(code_input, exec_globals) # Execute the user code550 551 # Check if the function `numIdenticalPairs` is defined552 if "numIdenticalPairs" in exec_globals:553 numIdenticalPairs = exec_globals['numIdenticalPairs'] # Get the function554 555 # Run the function on all test cases556 all_passed = True557 for i, case in enumerate(test_cases):558 input_val = case["input"]559 expected_val = case["expected"]560 561 try:562 result = numIdenticalPairs(input_val)563 if result == expected_val:564 st.write(f"Test case {i + 1} passed!")565 else:566 all_passed = False567 st.write(f"Test case {i + 1} failed: Expected {expected_val}, but got {result}")568 except Exception as e:569 all_passed = False570 st.write(f"Test case {i + 1} raised an error: {e}")571 572 if all_passed:573 st.success("All test cases passed!")574 else:575 st.error("Some test cases failed. Please review your code.")576 else:577 st.error("Function `numIdenticalPairs` not defined. Please define the function to proceed.")578 except Exception as e:579 st.error(f"Error executing code: {e}")580 581 # Display any print outputs or errors captured582 output = buffer.getvalue()583 if output:584 st.subheader("Execution Output:")585 st.text(output)586 587 588 589def Q5():590 st.title("1684. Count the Number of Consistent Strings")591 592 st.markdown("[Visit Leetcode](https://leetcode.com/problems/count-the-number-of-consistent-strings/description/) for a better experience.")593 594 # Create two columns: left for question, right for code input595 col1, col2 = st.columns(2)596 597 # Left column: Display the problem description598 with col1:599 st.write("""600 **Problem**: You are given a string `allowed` consisting of distinct characters and an array of strings `words`. 601 A string is consistent if all characters in the string appear in the string `allowed`.602 603 Return the number of consistent strings in the array `words`.604 605 **Example 1**:606 - Input: `allowed = "ab", words = ["ad","bd","aaab","baa","badab"]`607 - Output: `2` 608 - Explanation: Strings "aaab" and "baa" are consistent since they only contain characters 'a' and 'b'.609 610 **Example 2**:611 - Input: `allowed = "abc", words = ["a","b","c","ab","ac","bc","abc"]`612 - Output: `7` 613 - Explanation: All strings are consistent.614 615 **Example 3**:616 - Input: `allowed = "cad", words = ["cc","acd","b","ba","bac","bad","ac","d"]`617 - Output: `4` 618 - Explanation: Strings "cc", "acd", "ac", and "d" are consistent.619 620 **Constraints**:621 - `1 <= words.length <= 10^4`622 - `1 <= allowed.length <= 26`623 - `1 <= words[i].length <= 10`624 - The characters in `allowed` are distinct.625 - `words[i]` and `allowed` contain only lowercase English letters.626 """)627 628 # Create an expander for the topics629 with st.expander("Topics", expanded=False):630 st.write(""" 631 - **Strings**632 - **Hash Table**633 - **Array**634 - **Bit Manipullation**635 - **Counting** 636 """)637 638 with st.expander("Hint 1", expanded=False):639 st.write("A string is incorrect if it contains a character that is not allowed.")640 641 with st.expander("Hint 2", expanded=False):642 st.write("Constraints are small enough for brute force.")643 644 with st.expander("Sample Answer (NOTE: every question has different solutions)", expanded=False):645 st.code("""646def countConsistentStrings(allowed, words):647 ans = 0648 allowed = set(allowed) 649 650 for word in words: 651 word = set(word) 652 flag = True653 for ch in word:654 if ch not in allowed: 655 flag = False656 break657 ans += flag 658 659 return ans660 """)661 662 with st.expander("Flowchart of Sample Answer", expanded=False):663 st.image("images/intermediate/5.png")664 665 # Right column: Provide code editor for users to solve the problem666 with col2:667 st.header("Solve the Problem")668 669 # Display a code editor for the user to write their solution670 code_input = st.text_area(671 "Write your Python function here:",672 height=300,673 value="""674def countConsistentStrings(allowed, words):675 # Your code goes here676 pass677""")678 679 # Predefined test cases to evaluate the user's function680 test_cases = [681 {"input": ("ab", ["ad", "bd", "aaab", "baa", "badab"]), "expected": 2},682 {"input": ("abc", ["a", "b", "c", "ab", "ac", "bc", "abc"]), "expected": 7},683 {"input": ("cad", ["cc", "acd", "b", "ba", "bac", "bad", "ac", "d"]), "expected": 4},684 ]685 686 # Display the test cases in an expander687 for i, case in enumerate(test_cases):688 with st.expander(f"View Test Case {i + 1}", expanded=False):689 st.write(f"**Test Case {i + 1}:**")690 st.write(f"- Input: `{case['input']}`")691 st.write(f"- Expected Output: `{case['expected']}`")692 693 # Button to execute the code694 if st.button("Run Code"):695 buffer = io.StringIO()696 697 # Try to safely execute the user code698 try:699 # Redirect stdout to buffer and run the code700 with contextlib.redirect_stdout(buffer):701 exec_globals = {}702 exec(code_input, exec_globals) # Execute the user code703 704 # Check if the function `countConsistentStrings` is defined705 if "countConsistentStrings" in exec_globals:706 countConsistentStrings = exec_globals['countConsistentStrings'] # Get the function707 708 # Run the function on all test cases709 all_passed = True710 for i, case in enumerate(test_cases):711 input_val = case["input"]712 expected_val = case["expected"]713 714 try:715 result = countConsistentStrings(*input_val)716 if result == expected_val:717 st.write(f"Test case {i + 1} passed!")718 else:719 all_passed = False720 st.write(f"Test case {i + 1} failed: Expected {expected_val}, but got {result}")721 except Exception as e:722 all_passed = False723 st.write(f"Test case {i + 1} raised an error: {e}")724 725 if all_passed:726 st.success("All test cases passed!")727 else:728 st.error("Some test cases failed. Please review your code.")729 else:730 st.error("Function `countConsistentStrings` not defined. Please define the function to proceed.")731 except Exception as e:732 st.error(f"Error executing code: {e}")733 734 # Display any print outputs or errors captured735 output = buffer.getvalue()736 if output:737 st.subheader("Execution Output:")738 st.text(output)739 740 741def Q6():742 st.title("1614. Maximum Nesting Depth of the Parentheses")743 744 st.markdown("[Visit Leetcode](https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/description/) for a better experience.")745 746 # Create two columns: left for question, right for code input747 col1, col2 = st.columns(2)748 749 # Left column: Display the problem description750 with col1:751 st.write("""752 **Problem**: Given a valid parentheses string `s`, return the nesting depth of `s`. 753 The nesting depth is the maximum number of nested parentheses.754 755 **Example 1**:756 - Input: `s = "(1+(2*3)+((8)/4))+1"`757 - Output: `3`758 - Explanation: Digit 8 is inside of 3 nested parentheses in the string.759 760 **Example 2**:761 - Input: `s = "(1)+((2))+(((3)))"`762 - Output: `3`763 - Explanation: Digit 3 is inside of 3 nested parentheses in the string.764 765 **Example 3**:766 - Input: `s = "()(())((()()))"`767 - Output: `3`768 769 **Constraints**:770 - `1 <= s.length <= 100`771 - `s` consists of digits 0-9 and characters '+', '-', '*', '/', '(', and ')'.772 - It is guaranteed that parentheses expression `s` is a VPS (valid parentheses string).773 """)774 775 # Create an expander for the topics776 with st.expander("Topics", expanded=False):777 st.write(""" 778 - **Strings**779 - **Stack**780 """)781 782 with st.expander("Hint", expanded=False):783 st.write("The depth of any character in the VPS is the ( number of left brackets before it ) - ( number of right brackets before it ).")784 785 with st.expander("Sample Answer (NOTE: every question has different solutions)", expanded=False):786 st.code("""787def maxDepth(s):788 stk = []789 ans=0790 for x in s:791 if x=='(':792 stk.append(x)793 elif x==')' and stk and stk[-1] == '(':794 ans=max(ans,len(stk))795 stk.pop()796 return ans797 """)798 799 with st.expander("Flowchart of Sample Answer", expanded=False):800 st.image("images/intermediate/6.png")801 802 # Right column: Provide code editor for users to solve the problem803 with col2:804 st.header("Solve the Problem")805 806 # Display a code editor for the user to write their solution807 code_input = st.text_area(808 "Write your Python function here:",809 height=300,810 value="""811def maxDepth(s):812 # Your code goes here813 pass814""")815 816 # Predefined test cases to evaluate the user's function817 test_cases = [818 {"input": "(1+(2*3)+((8)/4))+1", "expected": 3},819 {"input": "(1)+((2))+(((3)))", "expected": 3},820 {"input": "()(())((()()))", "expected": 3},821 ]822 823 # Display the test cases in an expander824 for i, case in enumerate(test_cases):825 with st.expander(f"View Test Case {i + 1}", expanded=False):826 st.write(f"**Test Case {i + 1}:**")827 st.write(f"- Input: `{case['input']}`")828 st.write(f"- Expected Output: `{case['expected']}`")829 830 # Button to execute the code831 if st.button("Run Code"):832 buffer = io.StringIO()833 834 # Try to safely execute the user code835 try:836 # Redirect stdout to buffer and run the code837 with contextlib.redirect_stdout(buffer):838 exec_globals = {}839 exec(code_input, exec_globals) # Execute the user code840 841 # Check if the function `maxDepth` is defined842 if "maxDepth" in exec_globals:843 maxDepth = exec_globals['maxDepth'] # Get the function844 845 # Run the function on all test cases846 all_passed = True847 for i, case in enumerate(test_cases):848 input_val = case["input"]849 expected_val = case["expected"]850 851 try:852 result = maxDepth(input_val)853 if result == expected_val:854 st.write(f"Test case {i + 1} passed!")855 else:856 all_passed = False857 st.write(f"Test case {i + 1} failed: Expected {expected_val}, but got {result}")858 except Exception as e:859 all_passed = False860 st.write(f"Test case {i + 1} raised an error: {e}")861 862 if all_passed:863 st.success("All test cases passed!")864 else:865 st.error("Some test cases failed. Please review your code.")866 else:867 st.error("Function `maxDepth` not defined. Please define the function to proceed.")868 except Exception as e:869 st.error(f"Error executing code: {e}")870 871 # Display any print outputs or errors captured872 output = buffer.getvalue()873 if output:874 st.subheader("Execution Output:")875 st.text(output)876 877 878 879def Q7():880 st.title("1704. Determine if String Halves Are Alike")881 882 st.markdown("[Visit Leetcode](https://leetcode.com/problems/determine-if-string-halves-are-alike/description/) for a better experience.")883 884 # Create two columns: left for question, right for code input885 col1, col2 = st.columns(2)886 887 # Left column: Display the problem description888 with col1:889 st.write("""890 **Problem**: Given a string `s` of even length, split this string into two halves of equal lengths, 891 and let `a` be the first half and `b` be the second half.892 893 Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U').894 Return `true` if `a` and `b` are alike. Otherwise, return `false`.895 896 **Example 1**:897 - Input: `s = "book"`898 - Output: `true`899 - Explanation: `a = "bo"` and `b = "ok"`. `a` has 1 vowel and `b` has 1 vowel. Therefore, they are alike.900 901 **Example 2**:902 - Input: `s = "textbook"`903 - Output: `false`904 - Explanation: `a = "text"` and `b = "book"`. `a` has 1 vowel whereas `b` has 2. Therefore, they are not alike.905 906 **Constraints**:907 - `2 <= s.length <= 1000`908 - `s.length` is even.909 - `s` consists of uppercase and lowercase letters.910 """)911 912 # Create an expander for the topics913 with st.expander("Topics", expanded=False):914 st.write(""" 915 - **Strings**916 - **Counting**917 """)918 919 with st.expander("Hint", expanded=False):920 st.write("Create a function that checks if a character is a vowel, either uppercase or lowercase.")921 922 with st.expander("Sample Answer (NOTE: every question has different solutions)", expanded=False):923 st.code("""924def halvesAreAlike(s):925 cnt, cnt2, ln = 0, 0, len(s)926 vowels = set('aeiouAEIOU')927 for i in range(ln//2):928 if s[i] in vowels: cnt += 1929 if s[i+ln//2] in vowels: cnt2 += 1930 return cnt == cnt2931 """)932 with st.expander("Flowchart of Sample Answer", expanded=False):933 st.image("images/intermediate/7.png")934 935 # Right column: Provide code editor for users to solve the problem936 with col2:937 st.header("Solve the Problem")938 939 # Display a code editor for the user to write their solution940 code_input = st.text_area(941 "Write your Python function here:",942 height=300,943 value="""944def halvesAreAlike(s):945 # Your code goes here946 pass947""")948 949 # Predefined test cases to evaluate the user's function950 test_cases = [951 {"input": "book", "expected": True},952 {"input": "textbook", "expected": False}953 ]954 955 # Display the test cases in an expander956 for i, case in enumerate(test_cases):957 with st.expander(f"View Test Case {i + 1}", expanded=False):958 st.write(f"**Test Case {i + 1}:**")959 st.write(f"- Input: `{case['input']}`")960 st.write(f"- Expected Output: `{case['expected']}`")961 962 # Button to execute the code963 if st.button("Run Code"):964 buffer = io.StringIO()965 966 # Try to safely execute the user code967 try:968 # Redirect stdout to buffer and run the code969 with contextlib.redirect_stdout(buffer):970 exec_globals = {}971 exec(code_input, exec_globals) # Execute the user code972 973 # Check if the function `halvesAreAlike` is defined974 if "halvesAreAlike" in exec_globals:975 halvesAreAlike = exec_globals['halvesAreAlike'] # Get the function976 977 # Run the function on all test cases978 all_passed = True979 for i, case in enumerate(test_cases):980 input_val = case["input"]981 expected_val = case["expected"]982 983 try:984 result = halvesAreAlike(input_val)985 if result == expected_val:986 st.write(f"Test case {i + 1} passed!")987 else:988 all_passed = False989 st.write(f"Test case {i + 1} failed: Expected {expected_val}, but got {result}")990 except Exception as e:991 all_passed = False992 st.write(f"Test case {i + 1} raised an error: {e}")993 994 if all_passed:995 st.success("All test cases passed!")996 else:997 st.error("Some test cases failed. Please review your code.")998 else:999 st.error("Function `halvesAreAlike` not defined. Please define the function to proceed.")1000 except Exception as e:1001 st.error(f"Error executing code: {e}")1002 1003 # Display any print outputs or errors captured1004 output = buffer.getvalue()1005 if output:1006 st.subheader("Execution Output:")1007 st.text(output)1008 1009 1010def Q8():1011 st.title("2114. Maximum Number of Words Found in Sentences")1012 1013 st.markdown("[Visit Leetcode](https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/description/) for a better experience.")1014 1015 # Create two columns: left for question, right for code input1016 col1, col2 = st.columns(2)1017 1018 # Left column: Display the problem description1019 with col1:1020 st.write("""1021 **Problem**: A sentence is a list of words that are separated by a single space with no leading or trailing spaces.1022 You are given an array of strings `sentences`, where each `sentences[i]` represents a single sentence.1023 1024 Return the maximum number of words that appear in a single sentence.1025 1026 **Example 1**:1027 - Input: `sentences = ["alice and bob love leetcode", "i think so too", "this is great thanks very much"]`1028 - Output: `6`1029 - Explanation: The first sentence has 5 words, the second has 4, and the third has 6 words. The maximum is 6.1030 1031 **Example 2**:1032 - Input: `sentences = ["please wait", "continue to fight", "continue to win"]`1033 - Output: `3`1034 - Explanation: The second and third sentences contain the same number of words, which is 3.1035 1036 **Constraints**:1037 - `1 <= sentences.length <= 100`1038 - `1 <= sentences[i].length <= 100`1039 - `sentences[i]` consists only of lowercase English letters and ' ' only.1040 - `sentences[i]` does not have leading or trailing spaces.1041 - All the words in `sentences[i]` are separated by a single space.1042 """)1043 1044 # Create an expander for the topics1045 with st.expander("Topics", expanded=False):1046 st.write(""" 1047 - **Strings**1048 - **Array**1049 """)1050 1051 with st.expander("Hint", expanded=False):1052 st.write("Process each sentence separately and count the number of words by looking for the number of space characters in the sentence and adding it by 1.")1053 1054 with st.expander("Sample Answer (NOTE: every question has different solutions)", expanded=False):1055 st.code("""1056def mostWords(sentences):1057 m=01058 for i in sentences:1059 c=01060 for j in i:1061 if j == ' ':1062 c+=11063 m=max(m,c+1)1064 return m1065 """)1066 with st.expander("Flowchart of Sample Answer", expanded=False):1067 st.image("images/intermediate/8.png")1068 1069 # Right column: Provide code editor for users to solve the problem1070 with col2:1071 st.header("Solve the Problem")1072 1073 # Display a code editor for the user to write their solution1074 code_input = st.text_area(1075 "Write your Python function here:",1076 height=300,1077 value="""1078def mostWords(sentences):1079 # Your code goes here1080 pass1081""")1082 1083 # Predefined test cases to evaluate the user's function1084 test_cases = [1085 {"input": ["alice and bob love leetcode", "i think so too", "this is great thanks very much"], "expected": 6},1086 {"input": ["please wait", "continue to fight", "continue to win"], "expected": 3},1087 {"input": ["one", "two three", "four five six seven"], "expected": 4},1088 ]1089 1090 # Display the test cases in an expander1091 for i, case in enumerate(test_cases):1092 with st.expander(f"View Test Case {i + 1}", expanded=False):1093 st.write(f"**Test Case {i + 1}:**")1094 st.write(f"- Input: `{case['input']}`")1095 st.write(f"- Expected Output: `{case['expected']}`")1096 1097 # Button to execute the code1098 if st.button("Run Code"):1099 buffer = io.StringIO()1100 1101 # Try to safely execute the user code1102 try:1103 # Redirect stdout to buffer and run the code1104 with contextlib.redirect_stdout(buffer):1105 exec_globals = {}1106 exec(code_input, exec_globals) # Execute the user code1107 1108 # Check if the function `mostWords` is defined1109 if "mostWords" in exec_globals:1110 mostWords = exec_globals['mostWords'] # Get the function1111 1112 # Run the function on all test cases1113 all_passed = True1114 for i, case in enumerate(test_cases):1115 input_val = case["input"]1116 expected_val = case["expected"]1117 1118 try:1119 result = mostWords(input_val)1120 if result == expected_val:1121 st.write(f"Test case {i + 1} passed!")1122 else:1123 all_passed = False1124 st.write(f"Test case {i + 1} failed: Expected {expected_val}, but got {result}")1125 except Exception as e:1126 all_passed = False1127 st.write(f"Test case {i + 1} raised an error: {e}")1128 1129 if all_passed:1130 st.success("All test cases passed!")1131 else:1132 st.error("Some test cases failed. Please review your code.")1133 else:1134 st.error("Function `mostWords` not defined. Please define the function to proceed.")1135 except Exception as e:1136 st.error(f"Error executing code: {e}")1137 1138 # Display any print outputs or errors captured1139 output = buffer.getvalue()1140 if output:1141 st.subheader("Execution Output:")1142 st.text(output)1143 1144 1145 1146def Q9():1147 st.title("1941. Check if All Characters Have Equal Number of Occurrences")1148 1149 st.markdown("[Visit Leetcode](https://leetcode.com/problems/check-if-all-characters-have-equal-number-of-occurrences/description/) for a better experience.")1150 1151 # Create two columns: left for question, right for code input1152 col1, col2 = st.columns(2)1153 1154 # Left column: Display the problem description1155 with col1:1156 st.write("""1157 **Problem**: Given a string `s`, return true if `s` is a good string, or false otherwise.1158 1159 A string `s` is good if all the characters that appear in `s` have the same number of occurrences.1160 1161 **Example 1**:1162 - Input: `s = "abacbc"`1163 - Output: `true`1164 - Explanation: The characters that appear in `s` are 'a', 'b', and 'c'. All characters occur 2 times in `s`.1165 1166 **Example 2**:1167 - Input: `s = "aaabb"`1168 - Output: `false`1169 - Explanation: The characters that appear in `s` are 'a' and 'b'. 'a' occurs 3 times while 'b' occurs 2 times, which is not the same number of times.1170 1171 **Constraints**:1172 - `1 <= s.length <= 1000`1173 - `s` consists of lowercase English letters.1174 """)1175 1176 # Create an expander for the topics1177 with st.expander("Topics", expanded=False):1178 st.write(""" 1179 - **Strings**1180 - **Hash Table**1181 - **Counting**1182 """)1183 1184 with st.expander("Hint 1", expanded=False):1185 st.write("Build a dictionary containing the frequency of each character appearing in s")1186 1187 with st.expander("Hint 2", expanded=False):1188 st.write("Check if all values in the dictionary are the same.")1189 1190 with st.expander("Sample Answer (NOTE: every question has different solutions)", expanded=False):1191 st.code("""1192 1193def areOccurrencesEqual(s):1194 d = {}1195 1196 for i in s:1197 d[i] = d.get(i,0) + 11198 1199 values = list(d.values())1200 