-
Notifications
You must be signed in to change notification settings - Fork 5
/
leetcode-438-find-all-anagrams-in-a-string.swift
300 lines (223 loc) · 8.04 KB
/
leetcode-438-find-all-anagrams-in-a-string.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
/**
Copyright (c) 2020 David Seek, LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
https://leetcode.com/problems/two-sum/
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
*/
/**
Big O Annotation
Time complexity O(n) where n is the amount of characters in s.
Space complexity O(n) where n is the amount of characters in s and p.
*/
func findAnagrams(_ s: String, _ p: String) -> [Int] {
// If p is longer, than we can't find an anagram
guard s.count >= p.count else {
return []
}
// Get a character: count map from p
let map = getMapped(string: p)
// The length for easier access
let length = (p.count - 1)
/**
Get a character array from s
for easier index access
*/
let s: [Character] = Array(s)
// Out magical queue data structure
var queue = SuperQueue(start: Array(s[0...length]), map: map)
// The starting index
var index: Int = 0
// The result indices
var indices: [Int] = []
/**
Check if the initial substring
is an anagram of p
*/
if queue.isInitiallyAnAnagram() {
indices.append(index)
}
// Continue on the next elements
index = length + 1
// Until we have exhausted the string...
while index < s.count {
// Get the current character
let character = s[index]
// And add it to the queue with evaluation
if queue.add(character) {
indices.append(index - length)
}
// And proceed...
index += 1
}
return indices
}
/**
- parameters:
- string: The String p
- returns:
Returns a map of characters and their count in p.
Time and space complexity: O(n)
where n is the amount of characters in string.
*/
private func getMapped(string: String) -> [Character: Int] {
var map: [Character: Int] = [:]
for character in string {
map[character, default: 0] += 1
}
return map
}
/**
Queue Stack data structure.
Enqueue and dequeue have O(1) in time complexity.
The idea is, that we take string p as
initial map of characters and their counts.
Then we create a map of:
uses: characters and their counts
falses: characters and their counts
extras: characters and their counts
Every character in the processed substring
that was in the original map will go into uses
with the counts of usage.
Every character in the processed substring that
was NOT in the original map, will go into falses.
Every character of the original map that has NOT
been used by the initial processing,
will go into extras with the respective count.
For every new character we add,
we adjust those 3 dictionaries for
the character we're popping
and for the character we're adding.
IF extras and falses is isEmpty,
we found a new anagram of the original string
compared to the currently processed substring.
*/
struct SuperQueue {
private var enqueueStack: [Character] = []
private var dequeueStack: [Character] = []
private var map: [Character: Int]
private var uses: [Character: Int] = [:]
private var falses: [Character: Int] = [:]
private var extras: [Character: Int] = [:]
init(start: [Character], map: [Character: Int]) {
self.enqueueStack = start
self.map = map
}
// Adds a new character to the queue
public mutating func enqueue(_ character: Character) {
enqueueStack.append(character)
}
// Drops a character from the queue
public mutating func dequeue() -> Character? {
if dequeueStack.isEmpty {
dequeueStack = enqueueStack.reversed()
enqueueStack.removeAll()
}
return dequeueStack.popLast()
}
/**
This function does the actual job.
Dequeues the least used character.
Adds the new one.
And checks for falses, extras and uses.
*/
public mutating func add(_ character: Character) -> Bool {
// Pop the first element in the queue
guard let popped = dequeue() else {
return false
}
/**
Check if this character had been a character
that was NOT in the original map
*/
if let mapped = falses[popped] {
// If so, remove it from falses
let newCount = mapped - 1
falses[popped] = (newCount > 0) ? newCount : nil
/**
Otherwise the character must
have been used and therefore...
*/
} else if let mapped = uses[popped] {
// We want to remove it from uses
let newCount = mapped - 1
uses[popped] = (newCount > 0) ? newCount : nil
// ... and add it back to extras
extras[popped, default: 0] += 1
}
// Add the new character
enqueue(character)
// And check if it's available in extras
if let mapped = extras[character] {
// If so, decrease the count in extras...
let newCount = mapped - 1
extras[character] = (newCount > 0) ? newCount : nil
// .. and add it to uses
uses[character, default: 0] += 1
} else {
// Otherwise add it to falses
falses[character, default: 0] += 1
}
/**
If extras and falses are
each empty, then we have found a new anagram
*/
return extras.isEmpty && falses.isEmpty
}
/**
Initial function to process
the very first substring.
This function will only be called on
the initial setup of the queue.
*/
public mutating func isInitiallyAnAnagram() -> Bool {
// Move everything into the dequeu stack
dequeueStack = enqueueStack.reversed()
enqueueStack.removeAll()
// Variable we will return...
var isValid: Bool = true
// For every element in the queue...
for character in dequeueStack {
// Check if we have the character available
if let mapped = map[character] {
// .. and adjust the count...
let newCount = mapped - 1
map[character] = (newCount > 0) ? newCount : nil
// .. also add it to uses
uses[character, default: 0] += 1
} else {
// ... otherwise add it to falses...
falses[character, default: 0] += 1
isValid = false
}
}
/**
If we're here, we would expect the map
to be empty, if that's not the case,
then we need to now dump everything
into the extras dictionary.
*/
for (key, value) in map {
extras[key] = value
}
return isValid
}
}