Skip to content

02 Tips & Tricks

mccornet edited this page Jul 25, 2021 · 14 revisions

Tips & Tricks

Math

  • Sum of consecutive integers: 1/2 * n * (n+1)

Python

  • If the number of iterations is known beforehand; use a for loop instead of while. (Example: merging two arrays, problem 11)

  • Avoid using max in every iteration

    if a < b: a = b  # a lot faster than using max
    a = max(a, b)
  • Merging sorted arrays is faster using sort due to the very clever timsort algorythm in python.

  • Use tuple unpacking to reverse a list in-place

    reverse, reverse.next, head = head, reverse, head.next
  • Squaring a value is faster than abs(), in c++ this is not the case LC 977

C++

  • Include these lines for a significant speed-up source
    ios::sync_with_stdio(false);
    cin.tie(NULL);

Clone this wiki locally