updated with iterative algorithm