JP Morgan Interview Question for Java Developers


Country: India
Interview Type: Written Test




Comment hidden because of low score. Click to expand.
1
of 1 vote

public static void permutation(String str) { 
    permutation("", str); 
}

private static void permutation(String prefix, String str) {
    int n = str.length();
    if (n == 0) System.out.println(prefix);
    else {
        for (int i = 0; i < n; i++)
            permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
    }
}

Credit: StackOverflow (via Introduction to Programming in Java)

- Flash May 14, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

This is a solution for python with the set suggestion to remove duplicates

def anagrams(word):
    if len(word) == 1: return word
    
    solutions = []
    for x in xrange(len(word)):
        solutions.extend(map(lambda y: word[x] + y,
                             anagrams(word[:x] + word[x+1:])))
    return set(solutions)

- Fernando May 16, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

@Flash <-- Try finding anagrams of "speedstar". You would find that there will be too many repetitions. Consider adding them to a set. In ZoomBA, this is what we do.

def anagrams( word ){
  indices = [0:size(word)].asList()
  // permutate the indices 
  // use the index to map to a word ( a tuple is index tuple )
  // collect into a set 
  from ( perm( indices ) , set() ) as { str($.o,'') as { word[$.o] } }
}
println( anagrams('test') )

Also note that, for a practical point of view, you can not use recursion. The depth would become too high, better to use next_higher_permutation, which is implicit in ZoomBA.

- NoOne May 15, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

@NoOne - Thanks for showing that. It's the case indeed.

Updated the Java code using a set for accurate results. It goes as -

import java.util.Set;
import java.util.HashSet;

public class Anagrams{
  
  public static void main(String[] args){
    Set<String> results = permute("ABCD");
    for(String r : results){
      System.out.println(r);
    }
  }
  
  public static Set<String> permute(String text){
    Set<String> result = new HashSet<String>();
    if(text == null) return null;
    else if(text.length() == 0) {
      result.add("");
      return result;
    }
    char firstChar = text.charAt(0);
    String remainingText = text.substring(1);
    
    Set<String> restPerms = permute(remainingText);
    for(String s : restPerms){
      for(int i = 0; i <= s.length(); i++){
        String permWord = createWordCombination(firstChar, s, i);  
        result.add(permWord);
      }
    }
    return result;
  }
  
  public static String createWordCombination(char firstChar, String word, int i){
    String first = word.substring(0,i);
    String last = word.substring(i);
    String result = first+firstChar+last;
    return result;
  }
}

- Flash June 17, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

//print all anagrams of a string
#include<iostream>
#include<cstring>

using namespace std;

void swap(char *a, char *b){
	char temp = *a;
	*a = *b;
	*b = temp;
}

void anagramUtil(char a[],int n,int index){
	if(index >= (n-1)){
		cout<<a<<endl;
		return;
	}

	for(int i=index+1;i<n;i++){
		swap(&a[i],&a[index]);
		anagramUtil(a,n,index+1);
		swap(&a[i],&a[index]); //backtrack
	}
	anagramUtil(a,n,index+1);
}

void anagrams(char a[],int n){
	anagramUtil(a,n,0);
}

int main(){
	char a[]="abcd";
	anagrams(a,strlen(a));
	return 0;
}

- Praveen Kumar August 24, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package src;

import java.util.*;
import java.lang.*;

class Main {
	public static void main(String[] args) {
		System.out.println(angrams("abb"));
	}
	static Set<String>  angrams(String in) {
		Set<Integer> indices = new HashSet<Integer>();
	
		for(int i = 0; i < in.length(); i++) {
			indices.add(i);
		}
		
		Set<String> out = new HashSet<String>();
		for(StringBuilder sb : angrams(in, indices)) {
			out.add(sb.toString());
		}
	
		return out;
	}
	
	static Set<StringBuilder>  angrams(String in, Set<Integer> indices) {
		Set<StringBuilder> out = new HashSet<StringBuilder>();
		if(indices.isEmpty()) {
			out.add(new StringBuilder());
			return out;
		}
		
	
		for(Iterator<Integer> it = indices.iterator(); it.hasNext();) {
			Integer i = it.next(); 
			
			Set<Integer> newIndices = new HashSet<Integer>(indices);
			newIndices.remove(i);
			for(StringBuilder suffix : angrams(in, newIndices)) {
				suffix.insert(0, in.charAt(i));
				out.add(suffix);
			}
		}

		return out;
	}
}

- sab30226 September 04, 2017 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More