Algorithms: No Repeats Please
This commit is contained in:
		
							parent
							
								
									ecad95a4e8
								
							
						
					
					
						commit
						96a5e6bff1
					
				
							
								
								
									
										37
									
								
								Algorithms/noRepeatsPlease.js
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										37
									
								
								Algorithms/noRepeatsPlease.js
									
									
									
									
									
										Normal file
									
								
							@ -0,0 +1,37 @@
 | 
				
			|||||||
 | 
					// https://www.freecodecamp.org/learn/coding-interview-prep/algorithms/no-repeats-please
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					function permAlone(str) {
 | 
				
			||||||
 | 
					  let noRepeatsCount = 0;
 | 
				
			||||||
 | 
					  noRepeatsCount += Number(!/(.{1})\1/.test(str));
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					  function swap(Arr, iA, iB) {
 | 
				
			||||||
 | 
					    const tmp = Arr[iA];
 | 
				
			||||||
 | 
					    Arr[iA] = Arr[iB];
 | 
				
			||||||
 | 
					    Arr[iB] = tmp;
 | 
				
			||||||
 | 
					  }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					  const strArr = str.split("");
 | 
				
			||||||
 | 
					  const strLength = strArr.length;
 | 
				
			||||||
 | 
					  // Heap's Algorithm as explained @ https://www.baeldung.com/cs/array-generate-all-permutations
 | 
				
			||||||
 | 
					  const c = Array(strLength).fill(0);
 | 
				
			||||||
 | 
					  let i = 0;
 | 
				
			||||||
 | 
					  while (i < strLength) {
 | 
				
			||||||
 | 
					    if (c[i] < i) {
 | 
				
			||||||
 | 
					      if (i % 2) {
 | 
				
			||||||
 | 
					        swap(strArr, c[i], i);
 | 
				
			||||||
 | 
					      } else {
 | 
				
			||||||
 | 
					        swap(strArr, 0, i);
 | 
				
			||||||
 | 
					      }
 | 
				
			||||||
 | 
					      noRepeatsCount += Number(!/(.{1})\1/.test(strArr.join("")));
 | 
				
			||||||
 | 
					      c[i]++;
 | 
				
			||||||
 | 
					      i = 0;
 | 
				
			||||||
 | 
					    } else {
 | 
				
			||||||
 | 
					      c[i] = 0;
 | 
				
			||||||
 | 
					      i++;
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					  }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					  return noRepeatsCount;
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					console.log(permAlone("abcdefa"));
 | 
				
			||||||
		Loading…
	
		Reference in New Issue
	
	Block a user