Algorithmy
BAN USER 0of 0 votes
AnswersGiven this math equation, what is the value of x and y?
 Algorithmy in United States
x+y = 7
x^2+y^2 = 29
This was asked by one of the interviewers to my friend.
what about further generalizing this to:
x+y = 7
x^2+y^2 = 29
x^3+y^3 = 133
so on until k? Report Duplicate  Flag  PURGE
 0of 0 votes
AnswersFind compound words
 Algorithmy in United States
input> String (example "he has to go in a wheelchair")
output > wheelchair = wheel chair
assume that you have a big dictionary to look up the words.
Please help with this question asked in interview?. I want to also understand why a particular data structure was chosen and what is the time complexity. Report Duplicate  Flag  PURGE
You are displaying the elements that are connected to each other. The question is to identify the elements that are adjacent (straight or diagonally). Is there a better answer using graph theory and better bigO time performance?
 Algorithmy May 27, 2015o(n^2)  is there a better way to do this using graph theory?
 Algorithmy May 27, 2015codified  the case for power 2
/**
* solveQuadraticEquation
*
* @param a
* @param b
* @param c
*/
private void solveQuadraticEquation(int a, int b, int c){
double root1 = 0;
double root2 = 0;
double discrimnant = b * b  4 * a * c;
if( discrimnant == 0 ){ //roots are equal
root1 = root2 = (b / (2 * a));
}
else if( discrimnant < 0 ){ //imaginary roots
}
else{
root1 = (b + Math.sqrt(discrimnant)) / (2 * a);
root2 = (b  Math.sqrt(discrimnant)) / (2 * a);
}
if( root1 < 0 ) root1 = 1 * root1;
if( root2 < 0 ) root2 = 1 * root2;
System.out.println((int) root1 + "," + (int) root2);
}

Algorithmy
December 10, 2014 perfect, thank you. i have updated the question little bit to also generalize.
for generalizations polynomial of degree k can be used however the computational complexity might increase
degree 3: cubic: ax^3+bx^2+cx+d
and so on
Optimistic locking  We make a note of the record was read using the version number (or, other data such as time stamp, etc). When the record is written back we update the record if there are not changes in the version number. If the record is dirty, we fail the update transaction and ask the process to retry again. We also have to careful to make sure that the updates are atomic so as to not result in toctou software bug. This approach is usually used in high volume web based system that might use a stateless protocol like http.
Pessimistic locking  We lock the record at the time of reading. No other process can update the record until the lock is released. Once the record is done, transaction is closed and record is updated.
Directed graph can have max = (n * (n1)) / 2 edges
Undirected graph can have max = (n * (n1))
A Tree can have max of n1 edges
Are u answering assuming that it is as tree?
java version 
/**
* Reverses the list  iterative
* reverse the list at kth element
* Complexity: O(n)
*/
public Node<AnyType> reverseKthElement(int k)
{
return head=reverseKthElement(this.head, k);
}
/**
* Reverses the list  iterative
* reverse the list at kth element
* Complexity: O(n)
*/
private Node<AnyType> reverseKthElement(Node<AnyType> head, int k)
{
Node<AnyType> prev, current, next;
prev = null;
next = null;
current = head;
int count = 0;
while(current != null && count < k)
{
next = current.next;
current.next = prev;
prev = current;
current = next;
count++;
}
if( next != null ){
head.next = reverseKthElement(next, k);
}
return prev;
}

Algorithmy
November 11, 2014 well explained solution found on Internet:
Given a linked list, write a function to reverse every k nodes (where k is an input to the function).
Example:
Inputs: 1>2>3>4>5>6>7>8>NULL and k = 3
Output: 3>2>1>6>5>4>8>7>NULL.
Inputs: 1>2>3>4>5>6>7>80>NULL and k = 5
Output: 5>4>3>2>1>8>7>6>NULL.
Algorithm: reverse(head, k)
1) Reverse the first sublist of size k. While reversing keep track of the next node and previous node. Let the pointer to the next node be next and pointer to the previous node be prev. See this post for reversing a linked list.
2) head>next = reverse(next, k) /* Recursively call for rest of the list and link the two sublists */
3) return prev /* prev becomes the new head of the list */
#include<stdio.h>
#include<stdlib.h>
/* Link list node */
struct node
{
int data;
struct node* next;
};
/* Reverses the linked list in groups of size k and returns the
pointer to the new head node. */
struct node *reverse (struct node *head, int k)
{
struct node* current = head;
struct node* next = NULL;
struct node* prev = NULL;
int count = 0;
/*reverse first k nodes of the linked list */
while (current != NULL && count < k)
{
next = current>next;
current>next = prev;
prev = current;
current = next;
count++;
}
/* next is now a pointer to (k+1)th node
Recursively call for the list starting from current.
And make rest of the list as next of first node */
if(next != NULL)
{ head>next = reverse(next, k); }
/* prev is new head of the input list */
return prev;
}
/* UTILITY FUNCTIONS */
/* Function to push a node */
void push(struct node** head_ref, int new_data)
{
/* allocate node */
struct node* new_node =
(struct node*) malloc(sizeof(struct node));
/* put in the data */
new_node>data = new_data;
/* link the old list off the new node */
new_node>next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Function to print linked list */
void printList(struct node *node)
{
while(node != NULL)
{
printf("%d ", node>data);
node = node>next;
}
}
/* Drier program to test above function*/
int main(void)
{
/* Start with the empty list */
struct node* head = NULL;
/* Created Linked list is 1>2>3>4>5>6>7>8 */
push(&head, 8);
push(&head, 7);
push(&head, 6);
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, 2);
push(&head, 1);
printf("\n Given linked list \n");
printList(head);
head = reverse(head, 3);
printf("\n Reversed Linked list \n");
printList(head);
getchar();
return(0);
}
Time Complexity: O(n) where n is the number of nodes in the given list.
 Algorithmy November 11, 2014This link has very good description of how map reduce works and also some use cases
highlyscalable.wordpress.com/2012/02/01/mapreducepatterns/
unclear, please remove the post or edit the question to make some sense
 Algorithmy November 11, 2014using kobane algorithm is best for time complexity
public class MaxSubArraySum {
public static void main(String[] args){
int[] source = {1, 2, 2, 3, 5, 8, 9};
int[] source1 = {1, 3, 2, 5, 7, 6, 1, 4, 11, 23};
int[] source2 = {52,9,5,1,13};
MaxSubArraySum mss = new MaxSubArraySum();
System.out.println(mss.MaxSubArraySum_BruteForce1(source));
System.out.println(mss.MaxSubArraySum_BruteForce1(source1));
System.out.println(mss.MaxSubArraySum_BruteForce1(source2));
System.out.println(mss.MaxSubArraySum_BruteForce2(source));
System.out.println(mss.MaxSubArraySum_BruteForce2(source1));
System.out.println(mss.MaxSubArraySum_BruteForce2(source2));
System.out.println(mss.MaxSubArraySum_DivideConquer(source, source.length));
System.out.println(mss.MaxSubArraySum_DivideConquer(source1, source1.length));
System.out.println(mss.MaxSubArraySum_DivideConquer(source2, source2.length));
System.out.println(mss.MaxSubArraySum_Kobane(source));
System.out.println(mss.MaxSubArraySum_Kobane(source1));
System.out.println(mss.MaxSubArraySum_Kobane(source2));
}
/**
* 0(n power 3)
* brute force
*
* @param input
* @return
*/
private int MaxSubArraySum_BruteForce1(int[] input){
//validation
if( input.length < 1 ) return 0;
int ans = Integer.MIN_VALUE;
int length = input.length;
for (int sub_array_size = 1; sub_array_size <= length; sub_array_size++) // O(n)
{
for (int start_index = 0; start_index < length; start_index++) // O(n)
{
if (start_index + sub_array_size > length) // Subarray exceeds
break; // array bounds
int sum = 0;
for (int i = start_index; i < (start_index + sub_array_size); i++) {
sum += input[i]; // O(n)
}
ans = Math.max(ans, sum);
}
}
return ans;
}
/**
* o(nlogn)
*
* @param input
* @param length
* @return
*/
private int MaxSubArraySum_DivideConquer(int[] input, int length){
if (length == 1) {
return input[0];
}
int mid = length / 2;
int[] leftArr = new int[mid];
int[] rightArr = new int[length  mid];
for(int i = 0; i < mid; i++ ){
leftArr[i] = input[i];
}
int count = 0;
for(int i = mid; i < length; i++ ){
rightArr[count] = input[i];
count++;
}
int left_MSS = MaxSubArraySum_DivideConquer(leftArr, mid);
int right_MSS = MaxSubArraySum_DivideConquer(rightArr, length  mid);
int leftsum = Integer.MIN_VALUE, rightsum = Integer.MIN_VALUE, sum = 0;
for (int i = mid; i < length; i++) {
sum += input[i];
rightsum = Math.max(rightsum, sum);
}
sum = 0;
for (int i = (mid  1); i >= 0; i) {
sum += input[i];
leftsum = Math.max(leftsum, sum);
}
int ans = Math.max(left_MSS, right_MSS);
return Math.max(ans, leftsum + rightsum);
}
/**
* 0(n power 2)
* brute force
*
* @param input
* @return
*/
private int MaxSubArraySum_BruteForce2(int[] input){
//validation
if( input.length < 1 ) return 0;
int ans = Integer.MIN_VALUE;
int length = input.length;
for (int start_index = 0; start_index < length; start_index++) // O(n)
{
int sum = 0;
for (int sub_array_size = 1; sub_array_size <= length; sub_array_size++) // O(n)
{
if (start_index + sub_array_size > length) // Subarray exceeds
break; // array bounds
sum += input[start_index + sub_array_size  1]; //Last element of the new Subarray
ans = Math.max(ans, sum);
}
}
return ans;
}
/**
* o(n)
* Kobane algorithm
*
* @param input
* @return
*/
private int MaxSubArraySum_Kobane(int[] input){
//validation
if( input.length < 1 ) return 0;
//init
int ans = input[0], sum = 0;
//handle negative numbers
for( int i = 0; i < input.length; i++ ){
ans = Math.max(input[i], ans);
}
if( ans < 0 )
return ans;
ans = 0; //reset answer
for( int i = 0; i < input.length; i++ ){
if(sum+input[i] < 0) {
sum = 0;
}
else{
sum = sum+input[i];
}
ans = Math.max(ans, sum);
}
return ans;
}
}

Algorithmy
November 11, 2014 Here is java version  would love to head any other solution which would reduce the time complexity.
output
Words: forum,four; Bulls: 2, Cows: 2
Words: Picture,epic; Bulls: 0, Cows: 4
Words: forum,four; Bulls: 2, Cows: 2
Words: Picture,epic; Bulls: 0, Cows: 4
public class CowsnBullsGame {
/**
* o(n square)
* @param playerA
* @param playerB
*/
private static void findCowsandBulls(String playerA, String playerB){
//if any of the strings are null, the game cannot be played
if( playerA == null  playerB == null ) return;
int bulls = 0;
int cows = 0;
//for the string selected by player A
for( int i = 0; i < playerA.length(); i++ ){
char runnerChar = playerA.charAt(i);
//run thru all the characters in word selected by player B
for( int j = 0; j < playerB.length(); j++ ){
char playerBChar = playerB.charAt(j);
//character match  change to lower because case does not matter
if( Character.toLowerCase(runnerChar) == Character.toLowerCase(playerBChar) ){
if( i == j ){ //position match
bulls++;
}
else{ //contains relation
cows++;
}
}
}
}
System.out.println("Words: " + playerA + "," + playerB + "; Bulls: " + bulls + ", Cows: " + cows);
}
/**
* o(m+n) //length of both the strings
* @param playerA
* @param playerB
*/
private static void findCowsandBullsWithArray(String playerA, String playerB){
//if any of the strings are null, the game cannot be played
if( playerA == null  playerB == null ) return;
int bulls = 0;
int cows = 0;
//put the string the array
List playerBList = new ArrayList();
for (char c : playerB.toCharArray()) {
playerBList.add(Character.toLowerCase(c));
}
//for the string selected by player A
for( int i = 0; i < playerA.length(); i++ ){
char runnerChar = Character.toLowerCase(playerA.charAt(i));
if( playerBList.contains(runnerChar)){
if( playerBList.indexOf(runnerChar) == i){ //position match
bulls++;
}
else{
cows++;
}
}
}
System.out.println("Words: " + playerA + "," + playerB + "; Bulls: " + bulls + ", Cows: " + cows);
}
public static void main(String[] args) {
CowsnBullsGame.findCowsandBulls("forum", "four");
CowsnBullsGame.findCowsandBulls("Picture", "epic");
CowsnBullsGame.findCowsandBullsWithArray("forum", "four");
CowsnBullsGame.findCowsandBullsWithArray("Picture", "epic");
}
}

Algorithmy
November 10, 2014 Instead of storing elements in stack, you can store objects in the stack with the structure below. Any time you insert you need to compare with the element on top in stack (peep) with the inserted values and fill the object with max value. this will allow O(1) time. you do the same for kth max but then stack is not right datastructure to use because of the requirement.
customdata{
int data;
int[] max; > store max, second max until K in order
}
Thank you, this is perfect solution. Please note that my dictionary is limited here. I used PatriciaTrie in Apache commons collections and here is working code 
import java.util.StringTokenizer;
import org.apache.commons.collections4.Trie;
import org.apache.commons.collections4.trie.PatriciaTrie;
/**
* find compound words
*
*/
public class CompoundWords {
/**
* compound words
* @param sentence
*/
private void isCompundWord(String sentence) {
// dictionary
Trie<String, String> trie = new PatriciaTrie<String>();
trie.put("a", "a");
trie.put("awhile", "awhile");
trie.put("while", "while");
trie.put("wheel", "wheel");
trie.put("wheelchair", "wheelchair");
trie.put("chair", "chair");
//get the tokens in the sentence
StringTokenizer st = new StringTokenizer(sentence);
while (st.hasMoreTokens()) {
String word = st.nextToken();
int N = word.length();
for (int i = 1; i < N; i++) {
String x = word.substring(0, i);
String y = word.substring(i, N);
if (trie.containsValue(x) && trie.containsValue(y)) {
//match
System.out.println(word + ":" + x + " " + y);
}
}
}
}
/**
* test program
* @param args
*/
public static void main(String[] args){
CompoundWords cw = new CompoundWords();
cw.isCompundWord("Is he on a wheelchair");
cw = new CompoundWords();
cw.isCompundWord("It took me awhile to adjust to it, too.");
}
}

Algorithmy
November 08, 2014 Thanks for replying. Any particular reason to use Trie?
 Algorithmy November 07, 2014Quora has good answer for this, uses dynamic programming.
Sorry, I cannot post links here.
I was asked the same question in one of the interviews and offcourse couldn't do well in the interview.
There is 2 questions related to elevators that get asked
1.) Object oriented design for elevator system
2.) Scheduling of the elevator which is another complicated subject.
The following below should help with 1.).
Please note that the below content is from one of the papers on internet. unfortunately, i cannot link the web document here. search in google for "elevator system object oriented design" and you should find more details on the problem. It is domain cmu.edu.

Car: The car is being controlled to move up and down (in different speeds), to makestops at floors when necessary.
Button: The ElevatorControl class also controls the button class, which further generalizes two subclasses CarCallButton and HallCallButton. The control object
communicates with the Button objects, get the information whether a button is pressedand in turn controls the illumination of Button lights.
Indicator: There are two kinds of indicators in the system, the CarPositionIndicator and the CarDirectionIndicator (i.e. the CarLantern). The indicators are controlled to show the information about the current position and moving direction of the car.
Safety: Whenever an emergency happens according to the definition of emergency brake trigger in the requirement documentation, the ElevatorControl commands the Safety

I was asked the same question in one of the interviews and offcourse couldn't do well in the interview.
There is 2 questions related to elevators that get asked
1.) Object oriented design for elevator system
2.) Scheduling of the elevator which is another complicated subject.
The following below should help with 1.).
Please note that the below content is from one of the papers on internet. unfortunately, i cannot link the web document here. search in google for "elevator system object oriented design" and you should find more details on the problem. It is domain cmu.edu.

Car: The car is being controlled to move up and down (in different speeds), to makestops at floors when necessary.
Button: The ElevatorControl class also controls the button class, which further generalizes two subclasses CarCallButton and HallCallButton. The control object
communicates with the Button objects, get the information whether a button is pressedand in turn controls the illumination of Button lights.
Indicator: There are two kinds of indicators in the system, the CarPositionIndicator and the CarDirectionIndicator (i.e. the CarLantern). The indicators are controlled to show the information about the current position and moving direction of the car.
Safety: Whenever an emergency happens according to the definition of emergency brake trigger in the requirement documentation, the ElevatorControl commands the Safety

For any design question  one should first understand all the use cases.
for this question, let us simplify and consider the following use cases
1.) user can see the current time on the clock
2.) user can set/update the alarm (time, sound, ipod etc) for the clock
3.) clock needs to sound the alarm at the right time
4.) user can snooze/end the alarm.
In this problem, choosing an datastructure is not a big problem. The question might be around how you would design an alarm clock either objectoriented (or) system wise.
Classes:
Clock (Time (can use Calendar object), setTime(), getTime(), list of Alarm objects <Arraylist>)
Alarm (Time (can use Calendar object), setState(IAlarmState), call the right doAction() depending on value of AlarmStateEnum)
AlarmStateEnum  set, buzz, snooze, end
IAlarmState > doAction()
AlarmSetState implements IAlarmState ==> doAction can call an scheduled future java task to buzz the alarm.
AlarmEndState implements IAlarmState ==> doAction can cancel the scheduled future java task or end the buzzing alarm
AlarmBuzzState implements IAlarmState ==> doAction is an function that will play the sound
AlarmSnoozeState implements IAlarmState ==> doAction will call the clock to cancel the scheduled future java task and create a new one with the snoozed time.\
Please let me know any feedback or input.
below is solution for array of integer but should work for all types of data
1.) bruteforce  going thru the array and marking duplicates
2.) use an hashset to put data and it should remove duplicates
3.) sort and then compare with previous
public class RemoveDuplicates {
/**
* brute force o(N square)
*
* @param input
* @return
*/
public static int[] removeDups(int[] input){
boolean[] isSame = new boolean[input.length];
int sameNums = 0;
for( int i = 0; i < input.length; i++ ){
for( int j = i+1; j < input.length; j++){
if( input[j] == input[i] ){ //compare same
isSame[j] = true;
sameNums++;
}
}
}
//compact the array into the result.
int[] result = new int[input.lengthsameNums];
int count = 0;
for( int i = 0; i < input.length; i++ ){
if( isSame[i] == true) {
continue;
}
else{
result[count] = input[i];
count++;
}
}
return result;
}
/**
* set  o(N)
* does not guarantee order of elements returned  set property
*
* @param input
* @return
*/
public static int[] removeDups1(int[] input){
HashSet myset = new HashSet();
for( int i = 0; i < input.length; i++ ){
myset.add(input[i]);
}
//compact the array into the result.
int[] result = new int[myset.size()];
Iterator setitr = myset.iterator();
int count = 0;
while( setitr.hasNext() ){
result[count] = (int) setitr.next();
count++;
}
return result;
}
/**
* quicksort  o(Nlogn)
*
* @param input
* @return
*/
public static int[] removeDups2(int[] input){
Sort st = new Sort();
st.quickSort(input, 0, input.length1); //input is sorted
//compact the array into the result.
int[] intermediateResult = new int[input.length];
int count = 0;
int prev = Integer.MIN_VALUE;
for( int i = 0; i < input.length; i++ ){
if( input[i] != prev ){
intermediateResult[count] = input[i];
count++;
}
prev = input[i];
}
int[] result = new int[count];
System.arraycopy(intermediateResult, 0, result, 0, count);
return result;
}
public static void printArray(int[] input){
for( int i = 0; i < input.length; i++ ){
System.out.print(input[i] + " ");
}
}
public static void main(String[] args){
int[] input = {5,6,8,0,1,2,5,9,11,0};
RemoveDuplicates.printArray(RemoveDuplicates.removeDups(input));
System.out.println();
RemoveDuplicates.printArray(RemoveDuplicates.removeDups1(input));
System.out.println();
RemoveDuplicates.printArray(RemoveDuplicates.removeDups2(input));
}
}

Algorithmy
October 23, 2014 perfect
1.) we first compare length so that we will not get true result for "waterbottle" and "water".
2.) we add the 2 rotated strings in question so "erbottlewat" + "erbottlewat" = "erbottlewaterbottlewat". you will see that the original string "waterbottle" is substring of the string formed by adding 2 rotated strings.
My solution uses regex.
private static boolean matchPattern(String p,String ex)
{
ex=ex.replace("#",".+");
p=p.replaceFirst(ex,"");
if(p.equals(""))
{
return true;
}
return false;
}
public static void main(String[] args){
System.out.println(matchPattern("ABAB","A#B"));
System.out.println(matchPattern("abba","a#b"));
System.out.println(matchPattern("acbdaghfb","a#b"));
System.out.println(matchPattern("abcdacb","a#b"));
}

Algorithmy
October 23, 2014 perfect. Already sorted array on O(n) time.
Question: Is there any way that this problem can be solved in O(n) time if the array is not sorted?
/**
* find kth element
* o(n)
*/
public void findKthElement(int k)
{
if( head == null ){ //handle k >= length of list
return;
}
Node<AnyType> fast = head;
Node<AnyType> slow = head;
while(k > 0){
fast = fast.next;
k;
}
while(fast != null){
fast = fast.next;
slow = slow.next;
}
System.out.println("kth element value is: " + slow.data );
}

Algorithmy
October 23, 2014 /**
* find mid point
* 2 pointers  one more 2 times faste
*/
public void findMidPoint()
{
if( head == null ){
return;
}
Node<AnyType> fast = head;
Node<AnyType> slow = head;
while(true){
if( fast == null  fast.next == null ){
System.out.println("mid point value is: " + slow.data );
break;
}
fast = fast.next.next;
slow = slow.next;
}
}

Algorithmy
October 23, 2014 /**
* O(logn)
* find no of rotations  circularly sorted array, anticlockwise, no duplicates  binary
* no of rotation = index of min element
* @param source
* @param needle
* @return
*/
private int countRotationsBinary(int[] source){
int low = 0;
int high = source.length  1;
int length = source.length;
while( low <= high ){
if( source[low] <= source[high] ) return low; //case 1 (sorted array)
int mid = ( low + high ) / 2;
int next = (mid+1) % length;
int prev = (mid+length1) % length;
if( source[mid] <= source[prev] && source[mid] <= source[next] ) return mid; //case 2
if( source[mid] <= source[high] ) { high = mid  1; } //case 3  search left
if( source[mid] >= source[low] ) { low = mid + 1; } //case 4  search right
}
return 1;
}
the problem can be solved by using binary search in 0(logn) time. enjoy.
 Algorithmy October 23, 2014I think this question is related to performance of Iterative vs. Recursive fibonacci. The recursive operation becomes costly when the number becomes big because of the heavy call stack use.
Number N = 1's will be printed N1 times and 0's will be printed N2 times.
Number 4 = 1's  3 times, 0's  2 times
Number 10 = 1's  9 times, 0's  8 times
hope this helps.
public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i < Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
Thanks for answer in stackoverflow for below explanation:
If a number n is not a prime, it can be factored into two factors a and b:
n = a*b
If both a and b were greater than the square root of n, a*b would be greater
than n. So at least one of those factors must be less or equal to the square
root of n, and to check if n is prime, we only need to test for factors
less than or equal to the square root.
Hence if we search till sqrt of n, we are bound to find at least one factor
of n, which is enough to show that n is not prime.
perfect
 Algorithmy October 22, 2014Thanks to the post on stack overflow for the answer
/**
* Delete the node in single linked list given pointer to only that node
*
* The idea is to copy the data from the next node to the current node
* and delete the next node. The solution does not work if the node is the
* last node (This is what candidate has to debate and point out in interview)
*/
public void deleteNode(Node n){
if( n == null && n.next == null){
System.out.println("Cannot delete with out prev pointer");
}
n.data = n.next.data; //copy data from next element to this
Node temp = n.next; //store the next in temp
n.next = n.next.next; //point the next to next.next  delete node
temp = null; //release memory
}

Algorithmy
September 25, 2014 In java
same as C++ program above. Please include the check for K > size of the list.
1.) move the fast pointer to kth position
2.) move the fast and slow pointers by one
3.) exit when fast reached the end
4.) print the value of the slow pointer
public void findKthElement(int k)
{
if( head == null ){
return;
}
//add condition to handle k >= length of list
Node<AnyType> fast = head;
Node<AnyType> slow = head;
while(k > 0){
fast = fast.next;
k;
}
while(fast != null){
fast = fast.next;
slow = slow.next;
}
System.out.println("kth element value is: " + slow.data );
}

Algorithmy
September 25, 2014 Open Chat in New Window
perfect, produces the expected result.
 Algorithmy May 27, 2015