Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

O(n) -> O(k) #213

Closed
wants to merge 1 commit into from
Closed

O(n) -> O(k) #213

wants to merge 1 commit into from

Conversation

WenchaoD
Copy link
Contributor

@WenchaoD WenchaoD commented Mar 17, 2017

For this hunk:

if i - maxIdx.first! + 1 == k {
      maxIdx.removeFirst()
}

Same as:

if maxIdx.last! - maxIdx.first! + 1 == k {
      maxIdx.removeFirst()
}

As maxIdx.last! - maxIdx.first! + 1 is always less than or equal to maxIdx.count, and will poll the first element when it reachesk.
Such that : maxIdx.count is always less than or equal to k.

=> The space complexity is O(k), rather than O(n).

For this hunk:
```swift
if i - maxIdx.first! + 1 == k {
      maxIdx.removeFirst()
}
```
Same as: 

```swift
if maxIdx.last! - maxIdx.first! + 1 == k {
      maxIdx.removeFirst()
}
```
As `maxIdx.last! - maxIdx.first! + 1` is always less than or equal to `maxIdx.count`, and will pop the last element when it reaches`k`.
Such that :  `maxIdx.count` is always less than or equal to k.

=> The space complexity is `O(k)`, rather than `O(n)`.
@soapyigu
Copy link
Owner

I get your point, but this is linear, so that I use "n" represents it

@WenchaoD
Copy link
Contributor Author

Time is linear , which is correct as O(n), but space is O(k).

@WenchaoD
Copy link
Contributor Author

O. I get what u mean. Thanks.

@WenchaoD WenchaoD closed this Mar 18, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants