Skip to content

Tag: algorithm

Build tree from edge pairs and root

I’m trying to write a program that takes an array of edge pairs and turns it into a tree. I’m given a root. In this example, the root is 2. The only constraint is, each node can max have 2 children. Sample input: Expected output: Would look something like this: This is my attempt so far: Feel like…

how to generate spiral matrix in javascript?

I am trying to generate sprial matrix in javascript. question Given an integer A, generate a square matrix filled with elements from 1 to A^2 in spiral order. input : 3 when input is 4 my approach is to create 2d array with 0 value and after that they will fill values. Answer You could take loops for each edg…

Improve speed of my binary search algorithm

I have written a binary search algorithm in JavaScript: I wanted to ask if I can improve this algorithm to search faster or if some mistake is made here? EDIT: thank you guys for your help, this solution should work correctly now: Answer You are taking values as indices. If you take greater values than indice…