Swift | Two Pointers | Explained
Swift suffers the most during String Week because there\'s not a way to get the character at the index of a String in Swift in O(1) without converting it to a C
Swift suffers the most during String Week because there\'s not a way to get the character at the index of a String in Swift in $$O(1)$$ without converting it to a Character array first, which is itself an $$O(n)$$ process that results in $$O(n)$$ space complexity. Since we\'re only creating the character arrays to get around Swift\'s... unique limitations... it can be argued that solutions like this are *theoretically* $$O(1)$$ SC.\n\nAnyways, this problem, while initially difficult, can be simplified into the following rules:\n\n1. $$start$$ and $$target$$ must have the same order of L\'s and R\'s (i.e., they would be identical strings if all of their blank spaces were removed). This is because L\'s and R\'s cannot pass each other when moving pieces.\n2. An "L" in $$start$$ at index $$i$$ must have a corresponding "L" in $$target$$ at index $$j$$ such that $$i >= j$$. This is because $$start$$\'s "L" can move left but not right to match $$target$$.\n3. An "R" in $$start$$ at index $$i$$ must have a corresponding "R" in $$target$$ at index $$j$$ such that $$i <= j$$. This is because $$start$$\'s "R" can move right but not left to match $$target$$.\n\nWe can iterate two pointers through both strings, skipping blank spaces, and returning $$false$$ early if these properties are violated.\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$*\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```swift []\nclass Solution {\n    func canChange(_ start: String, _ target: String) -> Bool {\n        let (s, t) = (Array(start), Array(target))\n        let n = s.count\n        var i = 0, j = 0\n        while i < n || j < n {\n            while i < n && s[i] == "_" { i += 1 }\n            while j < n && t[j] == "_" { j += 1 }\n            if i == n || j == n { return i == n && j == n }\n            if (s[i] != t[j]) || (s[i] == "L" && i < j) || (s[i] == "R" && i > j) { return false }\n            (i, j) = (i+1, j+1)\n        }\n        return true\n    }\n}\n```
['Swift']