Working but still prob slow algorithm