DailyProgrammer Balancing Words Challenge
General Coding Advice


Do not use using namespace std.  See here and here.
Wrap your logic into a function.  This typically allows for better control flow.

// Returns the position that the word balances
// Returns 0 if the word does not balance (since words can never balance at 0)
int balances(const std::string&amp; word)
{
    // Some loop
        // If it balances return the position
        // Also note that a word can only balance in one position
    // End of loop
    // Return 0 since it does not balance
}

for (string&amp;&amp; word : input) {
    int pos = balances(word);
    if(pos)
    {
        // print something
    }
    else
    {
        // print something else
    }
}

Personally I would prefer using unsigned int or better yet size_t to index the string but you can run into problems using unsigned int so you can stick to int for now.


Faster stop condition

leftWeight is monotically increasing while rightWeight is monotonically decreasing.  So a faster stop condition is leftWeight &gt; rightWeight

Algorithm hint

You do not need to recompute everything each iteration.

Note that \$A\$, \$B\$, \$C\$, ... arbitrary values here and not letters in the alphabet.

Assume we have some number \$N_i = 5A + 4B + 3C + 2D + E\$ and we desire some number \$N_{i+1} = 4A + 3B + 2C + D\$.

It sure would be nice if we had some number \$M_i = A + B + C + D + E\$ so that \$N_{i+1} = N_i - M_i\$

But then how do we update \$M_i\$ to \$M_{i+1}\$ so that \$N_{i+2} = 3A + 2B + C = N_{i+1} - M_{i+1}\$?

And if for some reason we had \$N_{i+1}\$, \$M_{i+1}\$, and some new value \$E\$ could we use these to compute \$N_i\$?

If we could do all of the above \$O(1)\$ then our overall algorithm would be \$O(n)\$ instead of the \$O(n^2)\$ solution where you recalculate everything.