Guest User

main.py

a guest
Jul 25th, 2023
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.44 KB | Source Code | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. '''
  4. Input: "MICROSOFTISHIRING", num_rows=3:
  5. --------------------------------------
  6. M   O   T   I   G
  7. I R S F I H R N
  8. C   O   S   I
  9. => Output: "MOTIGIRSFIHRNCOSI"
  10.  
  11. Input: "MICROSOFTISHIRING", num_rows=4:
  12. --------------------------------------
  13. M     O      I
  14. I   S F    H R
  15. C O   T  S   I  G
  16. R     I      N
  17. => Output: "MOIISFHRCOTSIGRIN"
  18.  
  19. Input: "A", num_rows = 1:
  20. ------------------------
  21. A
  22. => Output: "A"
  23.  
  24. Contraints:
  25. (1) num_rows >= 1
  26. (2) len(Input) >= 1
  27. (3) Time complexity: O(n)
  28. (4) Memory complexity: O(n)
  29. '''
  30.  
  31. def zigzag(s: str, num_rows: int):
  32.     # O(n) memory
  33.     sol = ''
  34.     # Amount of characters that will be saved is exactly len(s) -> O(n) memory
  35.     rows = [[] for _ in range(num_rows)] # num_rows = 2: rows = [[], []]
  36.     current_row = 0
  37.     if num_rows == 1:
  38.         next_row_dir = 0
  39.     else:
  40.         next_row_dir = -1
  41.  
  42.     # 0(n) time complexity
  43.     for c in s:
  44.         rows[current_row].append(c)
  45.         if current_row == 0 or current_row == num_rows - 1:
  46.             next_row_dir *= -1
  47.         current_row += next_row_dir
  48.  
  49.     # O(n) time complexity
  50.     for row in rows:
  51.         for c in row:
  52.             sol += c
  53.  
  54.     '''
  55.    Time: O(n) + O(n) = O(n)
  56.    Memory: O(n) + O(n) = O(n)
  57.    '''
  58.     return sol
  59.  
  60.  
  61. def main():
  62.     print(zigzag('MICROSOFTISHIRING', 3) == 'MOTIGIRSFIHRNCOSI')
  63.     print(zigzag('ABCD', 1) == 'ABCD')
  64.  
  65. if __name__ == '__main__':
  66.     main()
Advertisement
Add Comment
Please, Sign In to add comment