Skip to content

Instantly share code, notes, and snippets.

@bhaveshmunot1
Last active June 4, 2020 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhaveshmunot1/6310854c88807d4a811e0a00cafc75cc to your computer and use it in GitHub Desktop.
Save bhaveshmunot1/6310854c88807d4a811e0a00cafc75cc to your computer and use it in GitHub Desktop.
Examples to Understand Time Complexity.
int sum(vector<int> nums) {
int ans = 0; // 1
for (int i=0; i<nums.size(); i++) { // n times
ans += nums[i]; // 1
}
return ans; // 1
}
void efficient(vector<int> nums) {
int addition = sum(nums); // O(n). Note: Single line does not
// mean constant time.
for (int i=0; i<n; i++) { // n times
nums[i] = nums[i] + addition; // 1
}
}
void inefficient(vector<int> nums) {
for (int i=0; i<n; i++) { // n times
nums[i] = nums[i] + sum(nums); // O(n)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment