Improved brute force algorithm to return the match position