Given a string and an int n, return a string made of the first and last ‘ n’ chars from the string. The string length will be at least n.

Following are the test cases

Test cases Result Status
nTwice(Hello,2) Helo OK
nTwice(Chocolate,3) Choate OK
nTwice(java,1) ja OK

Java solution

package test;

public class Program18 {
	public static void main(String[] args) {
		Program18.nTwice("Hello", 2);
		Program18.nTwice("Chocolate", 3);
		Program18.nTwice("java", 1);
	public static String nTwice(String str, int n) {
		return str.substring(0, n) + str.substring(str.length() - n, str.length());

Javascript solution

const nTwice = (str, n) => {
    return str.substr(0, n) + str.substr(str.length - n, str.length);

console.log(nTwice("Hello", 2)); //Helo
console.log(nTwice("Chocolate", 3)); //Choate
console.log(nTwice("java", 1)); //ja

Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

Leave a Reply