 <p>You want to iterate limited by </p> <pre><code>words.length </code></pre> <p>not <code>M.length()</code></p> <p>Better to split and then use <code>HashSet&lt;String&gt;</code> <code>add(String)</code> method</p> <p>that would be <code>O(n)</code>, your existing solution is <code>O(n^2)</code></p>