简体   繁体   中英

What is the Big O of function

Current I am learning Data Structures and Algorithms. I want to know how to calculate space complexity and Big O of function. I have written a program that Capabilities first alphabet of each index of an array. Please suggest me better way of doing it.

 function capitalizeFirst(arr){ let result = []; function helper(array) { if (array.length === 0) return; let upperCassed = array[0][0].toUpperCase(); array[0].split(array[0][0]) array[0] = array[0].split(array[0][0]) array[0][0] = upperCassed result.push(array[0].join('')); helper(array.splice(1)); } helper(arr); return result; } console.log(capitalizeFirst(['banana', 'orange', 'mango'])); // ['banana', 'orange', 'mango'] // ['Banana', 'Orange', 'Mango']

There are multiple ways to solve this question. You can use arrow function or javascript function. Below is one possible solution:

function capitalizeFirstLetter(strArr) {
  strArr.forEach(function (item, index) {
   console.log(item.charAt(0).toUpperCase() + item.slice(1));
  });
}

capitalizeFirstLetter(['banana','mango']); 

Regarding the space complexity, it is the maximum memory space required by the algorithm and in this case, we are not using any extra space. Hence it is O(1).

For more details on time and space complexity you can refer: https://www.hackerearth.com/practice/basic-programming/complexity-analysis/time-and-space-complexity/tutorial/

Your method works, but for the purpose of calculating Big OI think it is rather complex. It tends to hide the fact that it just loops over an array one time, which would make it O(n) .

A simpler way is do exactly what the requirement asks, and only that - loop over the array capitalizing the first character of the string

 function capitalizeFirst(arr){ for(var i=0;i<arr.length;i++){ arr[i] = arr[i][0].toUpperCase() + arr[i].substring(1); } return arr; } console.log(capitalizeFirst(['banana', 'orange', 'mango'])); // ['banana', 'orange', 'mango'] // ['Banana', 'Orange', 'Mango']

There are, of course, many ways to write the above but a simple loop, with 2 simple string methods is probably the most straightforward. It is clear from this example that it is O(n) for the loop plus O(1) for each string operation - the result being still O(n) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM