Leetcode!
  • LeetCode!
  • My personal guide to Leetcode
  • Array
    • 11. Container With Most Water
    • 15. 3Sum
    • 219. Contains Duplicate II
    • 238. Product of Array Except Self
    • 245. Shortest Word Distance III
    • 392. Is Subsequence
    • 442. Find All Duplicates in an Array
    • 561. Array Partition I
    • 661. Image Smoother
    • 697. Degree of an Array
    • 723. Candy Crush
    • 832. Flipping an Image
  • Backtracking
    • 294. Flip Game II
    • 401. Binary Watch
    • 1079. Letter Tile Possibilities
  • Binary Search
    • 744. Find Smallest Letter Greater Than Target
    • 852. Peak Index in a Mountain Array
  • String
    • 6. ZigZag Conversion
    • 17. Letter Combinations of a Phone Number
    • 38. Count and Say
    • 521. Longest Uncommon Subsequence I
    • 544. Output Contest Matches
    • 937. Reorder Data in Log Files
  • Design
    • 251. Flatten 2D Vector
    • 281. Zigzag Iterator
  • Hash Table
    • 1. Two Sum
    • 508. Most Frequent Subtree Sum
    • 884. Uncommon Words from Two Sentences
    • 734. Sentence Similarity
  • Linked List
    • 2. Add Two Numbers
  • Unsorted
    • 917. Reverse Only Letters
  • Math
    • 43. Multiply Strings
    • 462. Minimum Moves to Equal Array Elements II
    • 553. Optimal Division
    • 800. Similar RGB Color
  • Greedy
    • 406. Queue Reconstruction by Height
    • 861. Score After Flipping Matrix
  • Tree
    • 701. Insert into a Binary Search Tree
    • 897. Increasing Order Search Tree
  • Divide and Conquer
    • 53. Maximum Subarray
  • Dynamic Programming
    • 62. Unique Paths
    • 63. Unique Paths II
    • 64. Minimum Path Sum
    • 120. Triangle
    • 198. House Robber
    • 213. House Robber II
    • 303. Range Sum Query - Immutable
    • 518. Coin Change 2
    • 750. Number Of Corner Rectangles
    • 337. House Robber III
  • Depth first search
    • 841. Keys and Rooms
  • Trie
    • 677. Map Sum Pairs
  • Two pointer
    • 42. Trapping Rain Water
Powered by GitBook
On this page
  • Approach 1: Front and Back switching
  • Approach 2: Minor improvements to Approach 1
  1. Unsorted

917. Reverse Only Letters

Approach 1: Front and Back switching

class Solution:
    def reverseOnlyLetters(self, S):
        """
        https://leetcode.com/problems/reverse-only-letters/description/
        :type S: str
        :rtype: str
        """
        if S == "":
            return ""
        S = list(S)
        i, j = 0, len(S) - 1
        while i < j:
            if S[i].isalpha() == False:
                i += 1
            if S[j].isalpha() == False:
                j -= 1
            else:
                S[i], S[j] = S[j], S[i]
                i += 1
                j -= 1
        return ''.join(S)

This approach required keeping track of two positions in the array where we stay until we can find valid characters, once we find two characters at the front and back, we will switch them.

Time Complexity: O(1), just indices

Space Complexity: O(n)

Approach 2: Minor improvements to Approach 1

Instead of increasing i and j one by one, it can be optimized by using nesting while loops to increment/decrement until the next character on both ends and swap when we find them

class Solution:
    def reverseOnlyLetters(self, S):
        """
        https://leetcode.com/problems/reverse-only-letters/description/
        :type S: str
        :rtype: str
        """
        if S == "": return ""
        le = len(S)
        S = list(S)
        i, j = 0, le - 1
        while i < j:
            while i < j and S[i].isalpha() == False:
                i += 1
            while j > i and S[j].isalpha() == False:
                j -= 1
            if i < j:
                S[i], S[j] = S[j], S[i]
                i += 1
                j -= 1
        return ''.join(S)

The runtime and space complexity remains the same

Time Complexity: O(1), just indices

Space Complexity: O(n)

Previous2. Add Two NumbersNext43. Multiply Strings

Last updated 6 years ago