Leetcode Snippet

󰃭 2024-10-02


Do x in a geek way

Iterate over eight neighbors

289. Game of Life

for(int I = max(0, i-1); I < min(m, i+2); ++I)
    for(int J = max(0, j-1); J < min(n, j+2); ++J)
        // do something with neighbors;
        // be aware arr[I][J] is also included;

Iterate over four neighbors

int offsets[5] = {-1, 0, 1, 0, -1};
for(int dir = 0; dir < 4; dir++)
    doSomething(arr[i+offsets[dir]][j+[offsets[i+1]]])

use prime instead of unordered_map<char,int> as a key

49. Group Anagrams

constexpr array<char, 26> primes = {2,  3,  5,  7,  11, 13, 17, 19, 23,
                                    29, 31, 37, 41, 43, 47, 53, 59, 61,
                                    67, 71, 73, 79, 83, 89, 97, 101};

unordered_map<double, vector<string>> mp;
for(string &s: strs) {
    double d = 1;
    for(char &c: s) d *= primes[c-'a'];
    mp[d].push_back(s);
}

Infame optimization

#pragma GCC optimize("Ofast,unroll-loops")
#pragma GCC target("avx2,tune=native")

static int x = []() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    return 0;
}();

#pragmas are equivalent to command line flages to control the compiler’s behaviour. Cause we submit source code to a machine we can not interact with.

std::ios::sync_with_stdio(false); disables the synchronization between C and C++ streams. This means that they will have their own buffer.

    // This could be barfoobaz or foobarbaz or foobazbar;
    cout << "foo"; println("bar"); cout << "baz";

std::cin.tie(nullptr); unties cin from cout. Tied streams ensures that one is flushed automatically before each I/O operation on the other stream.

    cout << "Input name:";
    cin >> name;

If streams are untied, you might see a black screen blocked for waiting input.